使用jQuery在div中水平居中显示不同宽度的图像
我有以下部门:使用jQuery在div中水平居中显示不同宽度的图像,jquery,html,css,Jquery,Html,Css,我有以下部门: <div id="photos"> <div id="photos_cycle"> <img id="photo" src="{{ asset('bundles/tcheetenweb/images/photos/female_tennis_player.jpg') }}" /> <img id="photo" src="{{ asset('bundles/tcheetenweb/images/photos/foto_1.j
<div id="photos">
<div id="photos_cycle">
<img id="photo" src="{{ asset('bundles/tcheetenweb/images/photos/female_tennis_player.jpg') }}" />
<img id="photo" src="{{ asset('bundles/tcheetenweb/images/photos/foto_1.jpg') }}" />
<img id="photo" src="{{ asset('bundles/tcheetenweb/images/photos/foto_2.jpg') }}" />
<img id="photo" src="{{ asset('bundles/tcheetenweb/images/photos/foto_3.jpg') }}" />
</div>
</div>
它在8秒后循环图像,这里没有什么令人兴奋的
现在,我想根据图像的宽度将其居中,我确定照片的宽度\u循环应如何,以便我可以将其居中:
setInterval(function () {
$("#photos_cycle img").each(function() {
imageWidth = this.clientWidth;
if (imageWidth > 0) {
$("#photos_cycle").css('width', imageWidth);
});
}, 10);
唯一的问题是它可以在Firefox和Chrome中使用,但不能在IE中使用。。。
我发现其中最大的问题是,我无法确定要检查的图像大小,因为它们都有相同的id
我希望有人能帮我
一个活生生的例子可以在下面找到,看看右下角的方块
编辑:
我不想唯一地定义ID,因为稍后我想使用一些PHP代码将图像自动添加到photos\u cycle div
这是我用于div的css:
#photos {
background-color: #8ab7e2;
width: 340px;
height: 240px;
position: relative;
top: 60px;
border-radius: 20px;
-moz-border-radius: 20px;
box-shadow: 0px 0px 1px 1px #000;
}
#photos_cycle {
height: 240px;
margin: 0 auto;
position: relative;
}
#photos_cycle img {
display: block;
height: 200px;
margin-top: 18px;
position: position:absolute;
left:50%;
border: 2px solid #000;
border-radius: 5px;
-moz-border-radius: 5px;
}
元素不应具有相同的ID。ID必须唯一
这个问题实际上可以用CSS解决。只需使用文本对齐:居中代码>样式以使图像在div内居中
#photos_cycle { text-align: center; }
以下是如何通过jQuery将图像中心化:
<style type="text/css">
#your_image_id {
position:absolute;
left:50%;
top:100px;
}
</style>
<script>
$(document).ready(function() {
var width = $("#your_image_id").width();
var margin = width/2;
$("#your_image_id").css("margin-left","-"+margin);
});
</script>
#您的\u图像\u id{
位置:绝对位置;
左:50%;
顶部:100px;
}
$(文档).ready(函数(){
var width=$(“#您的_图像_id”).width();
var裕度=宽度/2;
$(“#您的#图像_id”).css(“左边距”,“-”+边距);
});
这样做的目的是,它从屏幕左侧留出50%的边距,并将图像向左移动,宽度为/2像素,即图像的宽度。有一个小型jQuery插件可以实现这种跨浏览器功能:
这个问题不清楚。你为什么要设置图像宽度?为什么要投他的反对票?他展示了他的代码,很好地表达了他的问题。我们不应该仅仅因为他的代码有问题就否决一个问题。感谢您的支持,如果问题不清楚,请澄清不清楚的内容,以便我可以将其添加到问题中。现在我的帖子似乎有一个-1,它还会被看到吗?这只会在图像更小或与div相同宽度的情况下起作用。
<style type="text/css">
#your_image_id {
position:absolute;
left:50%;
top:100px;
}
</style>
<script>
$(document).ready(function() {
var width = $("#your_image_id").width();
var margin = width/2;
$("#your_image_id").css("margin-left","-"+margin);
});
</script>