【问题标题】:Moving elements in DOM on resize using Javascript使用 Javascript 在调整大小时移动 DOM 中的元素
【发布时间】:2021-10-15 21:40:23
【问题描述】:

首先,请注意我在这个项目中使用的是 Elementor Pro,然后我不能轻易使用 css,因为 html 结构很复杂。这就是为什么我尝试使用 Javascript 来做到这一点。

我想将我的图片移动到平板电脑和移动设备的 h1 标题上方,并且在大屏幕上它保持在说明上方。

这是我的代码(纯 javascript,没有 jquery)

let title = document.getElementById("product-title");
let image = document.getElementById("product-image");
let resizeProductPage = function () {
        if(typeof(title) != 'undefined' && title != null){
            let width = window.innerWidth;
            if (width<1025)
                title.parentNode.insertBefore(image, title);
            else
                image.parentNode.insertBefore(title, image);
        }
  };
resizeProductPage();
window.addEventListener("resize", resizeProductPage);

但它不起作用,而且我发现代码相当复杂。你有什么想法吗?

【问题讨论】:

  • 你做了什么调试?这些元素有那些 ID 吗?宽度是否足够小以改变事物?你有任何错误吗?该函数是否运行?
  • 旁注:由于title 指的是一个元素(或null),所以您的if 可以只是if (title)。元素是真的,null 是假的。
  • 假设元素存在并且函数被调用,应该可以工作:codesandbox.io/s/re-so-question-68758748-ckr5b

标签: javascript html wordpress dom elementor


【解决方案1】:

您的代码似乎没问题,但这是您应该做的。

  1. 在使用 elementor 编辑下,在组件编辑器中,您 应该能够将标题元素的 ID 指定为:product-title 和图像元素的 ID:product-image
  2. 您的条件检查是否存在 title 元素应仅适用于 if (title),因为如果该元素不存在,它将返回 false。

除了您的代码应该可以正常工作之外,我还制定了一个可行的解决方案作为 sn-p。

let title = document.getElementById("product-title");
let image = document.getElementById("product-image");
let resizeProductPage = function() {
  if (title) {
    if (window.innerWidth < 1025)
      title.parentNode.insertBefore(image, title);
    else
      image.parentNode.insertBefore(title, image);
  }
};
resizeProductPage();
window.addEventListener("resize", resizeProductPage);
#product-image {
  background: black;
  text-align: center;
  height: 200px;
  width: 400px;
}

#product-image p {
  color: #fff;
}
<h1 id="product-title">Product Title</h1>
<div id="product-image">
  <p>Image Here</p>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-02
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多