Determine if element is inside or outside visible area of containing element
How do I determine if the .circle
elements in the code below are still "onscreen"? That is are they outside the visible area of the containing #wrapper
element?
Here's the code:
<html>
<style type="text/css">
body {
background-color: #000;
margin: 2px;
padding: 0;
}
#wrapper {
background-color: #ccf;
height: 100%;
width: 100%;
overflow: hidden;
position: relative;
}
.circle {
background-color: #fff;
width: 80px;
height: 80px;
border-radius: 40px;
-moz-border-radius: 40px;
position: absolute;
left: 0px;
top: 0px;
}
.stopped {
background-color: #ccc;
}
</style>
<!-- And this script: -->
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function randomDirection(){
var directions = ['+=','+=','+=','-='];
var direction = directions[Math.floor(Math.random()*directions.length)]
var amount = Math.floor(Math.random()*40);
var unit = 'px';
return direction + amount + unit;
}
$(document).ready(function(){
开发者_Python百科 var again = function() {
$('.circle:not(".stopped")').each(function(){
$(this).animate({
top: randomDirection(), left: randomDirection()
}, 300);
});
setTimeout(again, 300);
}
for (var i=0; i< 50; i++) {
$('.circle:first').clone().appendTo('#wrapper');
}
$('.circle').click(function(){
$(this).addClass('stopped');
});
again();
});
</script>
<!-- and this body -->
<body><div id="wrapper"><div class="circle"> </div></div></body>
</html>
Basically I want to add the .stopped
class once the .circle
element has left the visible area of the #wrapper
element.
something like
$('.circle.runned').each(function(){
if($(this).offset().left + $(this).width < $('#wraper').offset().left
|| $(this).offset().left > $('#wraper').width()
|| $(this).offset().top + $(this).height < $('#wraper').offset().top
|| $(this).offset().top > $('#wraper').height()
){
$(this).removeClass('runned').addClass('stopped');
}
});
Update from artlung: I modified your code to match mine, and this works great, replacing what I have:
var again = function() {
// not_stopped = $('.circle:not(".stopped")');
// $('#debug').text(not_stopped.length)
$('.circle:not(".stopped")').each(function(){
if ($(this).offset().left + $(this).width < $('#wrapper').offset().left
|| $(this).offset().left > $('#wrapper').width()
|| $(this).offset().top + $(this).height < $('#wrapper').offset().top
|| $(this).offset().top > $('#wrapper').height()
){
$(this).addClass('stopped');
} else {
$(this).animate({
top: randomDirection(), left: randomDirection()
}, 300);
}
});
setTimeout(again, 300);
精彩评论