【问题标题】:I am trying to set the z-index for an image but it's not working我正在尝试为图像设置 z-index,但它不起作用
【发布时间】:2021-11-07 13:33:35
【问题描述】:

我正在尝试为图像设置 z-index,但它不起作用。实际上,这个位置是绝对的,而且我已经用这段代码检查了父母的 z-index 以确保 z-index 没有。

var el = document.getElementById("bear-moving"); // or use $0 in chrome;
do {
    var styles = window.getComputedStyle(el);
    console.log(styles.zIndex);
} while(el.parentElement && (el = el.parentElement));

我的图像随着滚动而移动,需要居中。如果我设置 z-index,它只会在它开始移动之前起作用。

这段代码代表JS移动图片。

var container = document.getElementsByClassName('elementor-element-192d237');
var image1 = document.getElementById('bear-moving');
var index = 0;
document.addEventListener("scroll", () => {

    div = document.querySelector(".elementor-element-192d237");
  if(parseInt(div.getBoundingClientRect().top)-300 < 0 && parseInt(div.getBoundingClientRect().bottom)>430) {
      var style_top = 0;
    while (style_top<window.innerHeight/2-div.getBoundingClientRect().top-25) {
        style_top = style_top+5;
        image1.style.top = style_top + 'px';
    }

  }
})

【问题讨论】:

  • 请提供一个最小的例子
  • 看起来你没有在 img 上设置 z-index,所以很有可能你没有找到正确的 DOM 元素。这是一个快速猜测,没有看到您尝试设置 z-index 的实际代码。你能用codepen发布一个链接吗?
  • 这是两个不同的例子。首先,没有 z-index。在第二张图片中,z-index 已经设置好了。我无法提供示例,因为它是整个页面,但我可以为您提供链接,您可以在其中看到即使您从开发人员控制台设置 z-index,也不会发生任何事情。 ayro.ro/servicii/#dezvoltare-aplicatii-web
  • 您好,请阅读stackoverflow.com/help/minimal-reproducible-example 以帮助您将相关代码放入您的问题中。
  • 我使用的是 Wordpress 的 Elementor,所以它不是自定义代码。我可以编辑 css,添加一些 javascript,但是 html 代码是由 Elementor 编写的,正如您在开发者控制台中看到的那样。

标签: javascript html css z-index


【解决方案1】:

经过数小时尝试设置 z-index 并猜测问题所在,我发现这是一个背景透明图像...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-13
    • 2021-09-07
    • 2019-11-13
    • 2023-01-30
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    相关资源
    最近更新 更多