问题
The layout looks like this:

Basically all I want is to find out if the ELEMENT went outside the PAGE :)
All I know is the page width, which is fixed @ 900 px...
回答1:
Calculate the element's width
, then get its left
, finally subtract it to the page's width
and you'll get the overflow.
var pageWidth = $(".page").width();
var elementWidth = $(".element").width();
var elementLeft = $(".element").position().left;
if (pageWidth - (elementWidth + elementLeft) < 0) {
alert("overflow!");
} else {
alert("doesn't overflow");
}
.page {
overflow: hidden;
width: 200px;
height: 200px;
position: relative;
background: black;
}
.element {
width: 100px;
height: 100px;
position: absolute;
background: blue;
top: 10px;
left: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page">
<div class="element">
</div>
</div>
Example here: http://jsfiddle.net/jackJoe/Q5FdG/
回答2:
Assuming you have some <div id="elem"></div>
on your page, you could tell if it is outside of the viewport like this:
var $elem = $('#elem'),
top = $elem.offset().top,
left = $elem.offset().left,
width = $elem.width(),
height = $elem.height();
if (left + width > $(window).width()) {
alert('Off page to the right');
}
if (top + height > $(window).height()) {
alert('Off page to the bottom');
}
回答3:
Have you tried using CSS to prevent it from happening?
pre { word-wrap:break-word; }
To iterate through every element on the page seems excessive, and it will take some time on a busy page. It is possible but not entirely practical.
回答4:
All the answers here have not checked if element is at top: negative value
or left: negative value
.
So that's why, I am giving a more correct or precise answer here.
var pageWidth = $(".page").width();
var pageHeight = $(".page").height();
var pageTop = $(".page").offset().top;
var pageLeft = $(".page").offset().left;
var elementWidth = $(".element").width();
var elementHeight = $(".element").height();
var elementTop = $(".element").offset().top;
var elementLeft = $(".element").offset().left;
if ((elementLeft >= pageLeft) && (elementTop >= pageTop) && (elementLeft + elementWidth <= pageLeft + pageWidth) && (elementTop + elementHeight <= pageTop + pageHeight)) {
// Its inside
alert('Inside');
} else {
//
alert('Outside');
}
.page {
overflow: hidden;
width: 200px;
height: 200px;
position: relative;
background: black;
}
.element {
width: 100px;
height: 100px;
position: absolute;
background: blue;
top: -10px;
left: -10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="page">
<div class="element">
</div>
</div>
Check Fiddle
来源:https://stackoverflow.com/questions/6866293/how-to-find-out-if-an-element-overflows-with-jquery