問題描述:用table布局顯示數據列表時,某列數據長度不確定時,一般會通過添加樣式使文字超出某個長度時顯示為...
,同時使用tooltip顯示出完整信息,此時需要編寫指令判斷文字寬度是否超出預定值,從而實現當文字顯示不全時給出提示框,文字顯示完全時無需給出提示框。
1. 指令代碼
(function () { 'use strict'; angular .module('demo') .directive('widthOverflow', widthOverflow); function widthOverflow () { var directive = { restrict: 'A', scope: { enableTooltip: '=' }, link: linker }; return directive; function linker (scope, element, attrs) { var onMouseOver = function () { var $el = $(element); if ($el[0].offsetWidth < $el[0].scrollWidth) { scope.enableTooltip = true; } else { scope.enableTooltip = false; } scope.$apply(); }; element.on('mouseover', onMouseOver); element.bind('$destroy', function () { element.unbind('mouseover'); }); } } })();
2. html頁面引用指令
<span class="text-ellipsis" style="width: 100px;" width-overflow enable-tooltip="enableTooltip" uib-tooltip="完整的文字信息" tooltip-enable="enableTooltip"> 完整的文字信息 </span> <style> .text-ellipsis{ font-weight: normal; display: inline-block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; cursor: default; } </style>