I have many DIV with the same class name, let save "wmplayer". I want to make sure that when these DIV get close to bottom of browser, let say 100px above the bot开发者_StackOverflowtom, they will have display:none. How do I do that with jQuery? Thanks
I didn't exactly understand what you want but I belive the following code will do the trick, or you can adapt to your specific scenario. It binds a resize event on the window DOM object, everytime the screen resizes it fires a custom event on all divs of that class. The event checks the innserWidth/Height of the browser screen, with those values it does some math with the div size and position to accomplish the goal. This code checks both close to the bottom and close to the right side of screen. If you don't want to check the right side, remove the the second IF.
var Constant= 100; //100 px
$(document).ready(function() {
$(window).resize(function() {
var x= $(window).attr("innerWidth");
var y= $(window).attr("innerHeight");
$("div.wmplayer").trigger("DisplayNoneEvent", [x,y]);
});
$("div.wmplayer").bind("DisplayNoneEvent", function(x, y) {
var top, left, divwidth, divheight;
top= this.css("top");
left= this.css("left");
divwidth= parseInt(this.css("width"));
if (top + divwidth > x + Constant) {
$("div.wmplayer").css({
"display": "none"
});
} else {
divheight= parseInt(this.css("height"));
if (left + divheight > y + Constant) {
this.css({
"display": "none"
});
}
else {
this.css({
"display": "block"
});
}
}
})
$(window).trigger("resize");
/* the previous line might not be necessary, I'm not sure. It triggers
the event once on pageload */
});
This only works on divs with absolute position, if you want to use with divs with relative position you need to get the position of the div relative to the window, not sure how to do it. I can only think of a recursive function to check all parents adding up all widths/heights until it reaches the document object. It's far too ugly, slow and bug prone to code. Maybe someone has a better idea on how to do it.
Note: parseint function doesn't work very well on IE6 and IE7 (not sure about IE8), you need to first manually remove the 'px' string from the end of the string returned by this.css("width").
You can use position()
. It fetches the top left position of the element relative to its parent. As for how to keep checking for this, you could use scroll()
which is fired whenever a scrollbar is trigged (but does not keep updating while scrolling iirc), just bind scroll to your document window ala $(window).scroll(function() { ... });
you can use css
e.g.
CSS
.nodisplay{
display:none;
}
<div class="wmplayer nodisplay" ></div>
精彩评论