/背景知識/
substring 方法用於提取字符串中介於兩個指定下標之間的字符
substring(start,end)
開始和結束的位置,從零開始的索引
參數描述
start 必需。一個非負的整數,規定要提取的子串的第一個字符在 stringObject 中的位置。
stop 可選。一個非負的整數,比要提取的子串的最后一個字符在 stringObject 中的位置多 1。如果省略該參數,那么返回的子串會一直到字符串的結尾。
返回值
一個新的字符串,該字符串值包含 stringObject 的一個子字符串,其內容是從 start 處到 stop-1 處的所有字符,其長度為 stop 減 start。
說明
substring 方法返回的子串包括 start 處的字符,但不包括 end 處的字符。
如果 start 與 end 相等,那么該方法返回的就是一個空串(即長度為 0 的字符串)。
如果 start 比 end 大,那么該方法在提取子串之前會先交換這兩個參數。
如果 start 或 end 為負數,那么它將被替換為 0
/實際應用:截取字符串多出來並用省略號[...]顯示/
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js 截取字符串多出來並用省略號...顯示</title> <style type="text/css"> .content{ width: 200px; margin: 100px auto; padding: 15px; background-color: orange; color: #fff; } .btn { float: right; background-color: #fff; color: #333; font-size: 12px; padding: 4px 8px; border-radius: 3px; margin-top: 5px; text-shadow: 0 0 1px rgba(0,0,0,.25); box-shadow: 0 0 1px rgba(0,0,0,.25); } .move{ -webkit-transition:all ease-in-out .35s; transition:all ease-in-out .35s; -webkit-animation:showIn 1.4s cubic-bezier(0, 0, 0.2, 1); animation:showIn 1.4s cubic-bezier(0, 0, 0.2, 1); -webkit-animation-fill-mode: backwards; -moz-animation-fill-mode: backwards; -o-animation-fill-mode: backwards; animation-fill-mode: backwards; } @keyframes showIn{ 0%{ opacity: .5;} 60%{transform: scale(1.2);} 100% { -o-transform: scale(1.0);opacity: 1.0;} } @-webkit-keyframes showIn{ 0%{ opacity: .5;height: 20%;} 60%{-webkit-transform: scale(1.2);} 100% { -webkit-transform: scale(1.0);opacity: 1.0;} } </style> </head> <body> <div class="content"> <span> substring 方法用於提取字符串中介於兩個指定下標之間的字符 substring(start,end) 開始和結束的位置,從零開始的索引 substring 方法返回的子串包括 start 處的字符,但不包括 end 處的字符。 如果 start 與 end 相等,那么該方法返回的就是一個空串(即長度為 0 的字符串)。 如果 start 比 end 大,那么該方法在提取子串之前會先交換這兩個參數。 如果 start 或 end 為負數,那么它將被替換為 0 </span><span class="btn">收縮</span> </div> <script type="text/javascript"> var oDiv=document.getElementsByTagName('div')[0]; var arr_span=document.getElementsByTagName('span'); var str=arr_span[0].innerHTML; var onOff=true; arr_span[1].onclick=function(){ if(onOff){ arr_span[0].innerHTML=str.substring(0,43)+'...'; arr_span[1].innerHTML='展開'; oDiv.classList.add('move'); onOff=false; }else{ arr_span[0].innerHTML=str; arr_span[1].innerHTML='收縮'; oDiv.classList.remove('move'); onOff=true; } } </script> </body> </html>