I have an image:
<img title="<?php echo JText::_('AEROBOT_HELLO'); ?>" src="images/aerobot.png" id="aerobot" align="right" /&开发者_如何学JAVAgt;
And I want to move the image (make it visible any time), when user scroll the page. I tried this code:
var $scrollingDiv = $("#aerobot");
$(window).scroll(function(){
$scrollingDiv
.stop()
.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );
});
But it's moving the whole content(which is under image) that I have on the page. So, how to move only the image with the scroll?
make the position:absolute
and adjust the top and left values:
img {z-index:1000;top:0; left:0;position:absolute;width: 300px; height: 50px; float:left;}
here is the code in example, minimize the browser for the scroll to show up
Example
to make it stay in its parent container, you have to put display:block to both of them, position:relative to the parent container. for right alignment put right:0 to the image;
img {
z-index:1000;
top:0;
position:absolute;
width: 350px;
height: 50px;
background-color:blue;
right:0;
display:block;
}
#parent{
width: 400px;
height: 400px;
background-color:red;
position:relative;
display:block;
}
Example 2
No need to use JS : use the CSS attribute position: fixed
. It acts like absolute positionning, but when the user scroll, the image doesn't move up or down.
精彩评论