通過css和js設定內容不確定的兩行文字兩端對齊
阿新 • • 發佈:2018-12-16
效果如圖所示:
思路:
1.先通過css樣式設定兩行兩端對齊,但是會有一個問題,隨著兩行的內容的不確定,沒辦法固定兩行的寬度,通過第二步解決
首先元素新增如下宣告達不到效果
text-align: justify;
然後對元素的父元素新增宣告 注意:(只給元素本身新增對齊的宣告)
text-align: justify;
text-align-last: justify;
text-justify: inter-ideograph;
2.通過就是的方法動態設定兩行的寬度,並讓其保持相等
resetRight(); window.onresize=function(){ resetRight(); } function resetRight(){ var wether1ScrollWidth= document.getElementById("wether1").scrollWidth; var wether2ScrollWidth= document.getElementById("wether12").scrollWidth; if(wether1ScrollWidth>=wether2ScrollWidth){ document.getElementById("wether12").style.width = wether1ScrollWidth+"px"; }else{ document.getElementById("wether1").style.width = wether2ScrollWidth+"px"; } }
全部程式碼貼在下面:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> New Document </title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style type="text/css"> .wether1{ font-family:Microsoft YaHei; position: absolute; font-size:28px; text-shadow:#000 0.5px 1px 0.5px;//設定文字投影 margin:5px 0 0 20px; color:#2DA6DB; text-align: justify; } .wether12{ text-shadow:#000 0.5px 1px 0.5px; color:#2DA6DB; position: absolute; font-size:15px; margin:45px 0 0 20px; text-align: justify; } .wetherDiv{ border:1px solid #2DA6DB; text-align: justify; text-align-last: justify; text-justify: inter-ideograph; height:100px; width:500px; } </style> </head> <body> <div id="wetherDiv" class="wetherDiv"> <span id="wether1" class="wether1">今天天氣很好</span> <span id="wether12" class="wether12">It's a nice day today</span> </div> </body> <script language="javascript"> resetRight(); window.onresize=function(){ resetRight(); } function resetRight(){ var wether1ScrollWidth= document.getElementById("wether1").scrollWidth; var wether2ScrollWidth= document.getElementById("wether12").scrollWidth; if(wether1ScrollWidth>=wether2ScrollWidth){ document.getElementById("wether12").style.width = wether1ScrollWidth+"px"; }else{ document.getElementById("wether1").style.width = wether2ScrollWidth+"px"; } } </script> </html>