假设我在h1元素中有一个标题(任何元素都可以)。它的内容是动态的(不知道标题的长度)。它应该显示在一行中。h1在一个有限大小的DIV(我们称之为容器)中。
如何知道元素(h1)是否溢出其容器(DIV)?
因此,如果它溢出,我会应用一个CSS类来处理这种情况。例如,我会将h1的隐藏内容滚动到视图中。
- 容器的宽度定义为相对于屏幕大小
示例:
#container {
width: 60%;
background-color: gray;
height: 50px;
// overflow: hidden;
position: relative;
}
h1 {
overflow: hidden;
height: 100%;
margin: 0;
line-height: 50px;
}
<div id="container">
<h1>a soft white or grey mineral consisting of hydrated calcium sulphate. It occurs chiefly in sedimentary deposits and is used to make plaster of Paris and fertilizers, and in the building industry.</h1>
</div>
最好的解决方案是,它可以用于:ngIf
中的primary,ngClass
指令中的secondary,但以下任何技术都是好的:Javascript
、AngularJS
、CSS
、AngularJS directive
。
假设jquery,您可以检查元素的宽度。
if ($('h1').scrollWidth > $('#container').innerWidth()) {
//overflown
}
这是我在AngularJS directive
中的解决方案。它不依赖于父元素:
var myDirective = angular.module('myDirective', []);
myDirective.directive( 'myDirective' , ['$timeout' , function($timeout) {
return {
link: function (scope , element , attrs) {
// Wait few milliseconds until element is re-rendered
// so that element properties reflect content size.
$timeout( function(){
if (element[0].scrollWidth > element[0].offsetWidth){
// overflow
}
}, 200); // $timeout
} // link
}; // return
}]); // myDirective
用法示例:
<h3 my-directive>Hello World!</h3>
注意:父元素的大小必须受到限制,否则它将根据内容进行调整,并且元素永远不会溢出