javascript - 使用绝对定位和 z-index 堆叠动态添加的图像

标签 javascript jquery html css

我有一组图像,我想将它们堆叠在一起。每个都有 position: absolute , top: 0 , left:0z-index按值(value)降序排列。只有具有最高 z-index 值的图像应该是可见的,所有其他图像都应该堆叠在它下面。

当然,容器 div ( <div id="slide-container"> ) 将有 position: relative

唯一的问题是,我正在动态添加这些图像,这可能是我没有获得所需行为的原因。

HTML

<div id="slide-container">

    <div class="icon-container">
        <i class="fa fa-arrow-left" aria-hidden="true"></i>
    </div>

    <div class="icon-container">
        <i class="fa fa-arrow-right" aria-hidden="true"></i>
    </div>

    <!-- Here I will be adding the images  -->
</div>

JS

var slides = [
    {
        img: 'images/one.jpg',
        text: 'First Image' 
    },
    {
        img: 'images/two.jpg',
        text: 'Second Image'
    },
    {
        img: 'images/Three.jpg',
        text: 'Second Image'
    }
];

var z = slides.length;

for(var index = 0; index < slides.length; index++,z--){

    var img = $('<img>');
    img.attr('src', slides[index].img);
    img.attr('height','100%');
    img.attr('width','97%');
    img.attr('class','stock-images');

    // the following properties doesn't seem to have any effect.
    img.attr('position','absolute');
    img.attr('left','0');
    img.attr('top','0');
    img.attr('z-index',z);

    $('#slide-container').append(img);

}

CSS

#slide-container{
    /*border: 1px solid lightgrey;*/
    height: 32em;
    width: 70%;
    margin-top: 1em;
    margin-left: auto;
    margin-right: auto;
    text-align: center; /*not required if image takes 100% width of container*/

    position: relative; /*kept it relative positioned*/
}

.icon-container:nth-child(1){
    /*left arrow icon*/
    position: absolute;
    left: -4em;
    top: 45%;
    color: #DFE0E3;
}

.icon-container:nth-child(2){
    /*right arrow icon*/
    position: absolute;
    right: -4em;
    top: 45%;
    color: #DFE0E3;
}

我没有得到预期的行为,而是所有图像都一个接一个地出现。我做错了什么?

谢谢!

最佳答案

在您的示例中,以下代码:

    var img = $('<img>');
    img.attr('src', slides[index].img);
    img.attr('height','100%');
    img.attr('width','97%');
    img.attr('class','stock-images');

在 HTML 文档中创建以下标签:

<img src="img_path_from_array" height="100%" width="97%" class="stock-images">

但是你想编辑这个元素的样式/css,所以你应该使用 .css 而不是使用 .attr ,如下所示:

img.attr('src', slides[index].img);
img.css('height','100%');
img.css('width','97%');

区分HTML元素的属性和HTML元素的样式属性(css)

关于javascript - 使用绝对定位和 z-index 堆叠动态添加的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45672181/

相关文章:

javascript - js删除提交的表单数据

javascript - jQuery 选择器 : match array attribute's n-th value

javascript - 智能div,如果在屏幕左端则向右移动div,反之亦然

javascript - 包裹在 setTimeout 中时出现错误 "Cannot read property of undefined"

php - 如何使用 PHP/HTML 保留空格格式?

javascript - Html Checkbox,多个具有相同的 'name' 。如果选中,值为 1,如果未选中,值为 0

javascript - 在 NetSuite 中将直运 PO 添加到现有销售订单

javascript - 如何在socket.io中使用事件?

javascript - 在 Protractor 中,我们如何迭代并为其中包含 $index 的 Angular 模型赋予不同的值?

javascript - 如何让 Google Apps 脚本执行 SHA-256 加密?