判斷文字寬度,給其新增title屬性
阿新 • • 發佈:2018-11-04
適用情況:有些選單文字超出範圍,將其超出的範圍隱藏,用'...'代替,再給其新增title屬性顯示全部,但是,不是每個選單都要加title屬性,這時就判斷文字寬度,進行判斷,只給超出範圍的新增title屬性。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>文字內容過長</title> <script type="text/javascript" src="js/jquery-1.7.js"></script> <style type="text/css"> </style> </head> <body> <div id="div1" onmouseover="mouseOver()" style="border: 1px solid #000;width: 200px"> <div id="div2" style="width:100px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; cursor: pointer;">測試測試測試測試測試測試測試</div> <div id="div3" style="display: none;"></div> </div> <script type="text/javascript"> function mouseOver() { //alert("123123213123123"); var div2text = $("#div2").html(); $("#div3").html(div2text); var width = $("#div3").width(); if (eval(width) >= 100) { $("#div2").attr("title",div2text); } } </script> </body> </html>