2017-04-07 97 views
0

我一直在特林同一位置设置img作为另一个使用jQuery .position().css()JQuery的设置两个IMGS以相同的位置,另一

这里是代码:

function setImgsToSamePosition() { 
    var position = $('#img1').position(); 
    $('#img2').css({ 'left': position.left + 'px', 'top': position.top + 'px' }); 
    $('#img3').css({ 'left': position.left + 'px', 'top': position.top + 'px' }); 
} 

$(document).ready(function() { 
    // Set imgs pos to be equal to img1 pos 
    setImgsToSamePosition(); 
}) 

有什么想法?

+0

删除'$''之前function'。 'function'是一个关键字。 –

+0

我确实删除了。还是行不通... – GreetingsFriend

回答

0

你可以用这种方式重叠图像。我将位置设置为fixed,然后为其他图像设置左侧和顶部值。我不完全确定你为什么要这样;所以,如果这不是理想的结果,只是评论。

function setImgsToSamePosition() { 
 
    var position = $('#img1').position(); 
 
    $('#img2, #img3').css({ 'left': position.left + 'px', 'top': position.top + 'px' }); 
 
} 
 

 
$(document).ready(function() { 
 
    // Set imgs pos to be equal to img1 pos 
 
    setImgsToSamePosition(); 
 
})
img { 
 
    width:100px; 
 
    height:100px; 
 
    border:1px solid black; 
 
} 
 

 
#img1, #img2, #img3 { 
 
    position:fixed; 
 
} 
 

 
#img1 { 
 
    left:50px; 
 
    top:50px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img id="img1" src="http://neil.computer/stack/bg.jpg" /> 
 
<img id="img2" src="http://neil.computer/stack/bg2.jpg" /> 
 
<img id="img3" src="http://neil.computer/stack/bg3.jpg" />

0

对于一个元素在此方式工作 位置的平移:相对; left:20px;

0

我不知道你到底是什么,但我只是纠正了你的代码。

$(function(){ 
 
    var position = $('#img1').position(); 
 
    var x = $("#img2").position(); 
 
    $("#pos").text("top: "+x.top+" "+"left: "+x.left); 
 
    $('#img3').css({ 'left': x.left + 'px', 'top': x.top + 'px' }); 
 
});
<html> 
 
<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
</head> 
 
<body> 
 
<img src="https://www.w3schools.com/css/img_fjords.jpg" id="img1" style="height:100px;width:100px;"/> 
 
<img src="https://www.w3schools.com/howto/img_mountains.jpg" id="img2" style="height:100px;width:100px;"/> 
 
<p id="pos"></p> 
 
</body> 
 
</html>

相关问题