如何从DOM中更改元素,然后在JavaScript中将其恢复为原始状态?

时间:2018-11-27 15:16:14

标签: javascript dom mouseover mouseout mutation

我已经创建了一个功能,该功能可以循环目标对象的DOM(通过id)以创建过渡功能。

我的问题出在rollOver/rollOut函数之内。由于某种原因,我运行此脚本的环境似乎与srcset属性混为一谈。

这是原始文件:

function rollOver(elem) {
  (document.getElementById(elem).srcset =
    "https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/eyes-on-you-desktop-hover-" +
    elem.slice(6) +
    ".jpg?$staticlink$"),
    "https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/eyes-on-you-desktop-2x-hover-" +
    elem.slice(6) +
    ".jpg?$staticlink$ 2x";
}

function rollOut(elem) {
  (document.getElementById(elem).srcset =
    "https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/eyes-on-you-desktop-" +
    elem.slice(6) +
    ".jpg?$staticlink$"),
    "https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/eyes-on-you-desktop-2x-" +
    elem.slice(6) +
    ".jpg?$staticlink$ 2x";
}

翻转:

path/to/image/eyes-on-you-desktop-hover-" + elem.slice(6) + ".jpg?$staticlink$"

推出:

path/to/image/eyes-on-you-desktop-" + elem.slice(6) +".jpg $staticlink$"

elem变量来自这里...

document.addEventListener("DOMContentLoaded", function (event) {
  var rollOverCollectionA = document
    .getElementById("roll-over-collection-b")
    .getElementsByClassName("rollover");
  rollOverCollectionA = Array.prototype.slice.apply(rollOverCollectionA);

  var l = rollOverCollectionA.length;
  for (let i = 0; i < l; i++) {
    on("mouseover", `#${rollOverCollectionA[i].id}`, function () {
      rollOver(rollOverCollectionA[i].id);
    });
    on("mouseout", `#${rollOverCollectionA[i].id}`, function () {
      rollOut(rollOverCollectionA[i].id);
    });
  }
});

以及元素上的#id值,该值被切成与正在接收焦点的元素重合。

我尝试过这样的事情:

  function rollOver(id, elem ) {
    elem.srcset = elem.srcset.splice(174, 0, '-hover');
    elem.srcset = elem.srcset.splice(362, 0, 'hover-')
    document.getElementById(id).srcset = elem.srcset;
  }

  function rollOut(id, elem) {
    document.getElementById(id).srcset = elem.srcset;
  }

但是这样做是在elem.srcset / string中不断添加'hover!

更新

这是有效的demo

更新

这是正在发生的事的一个例子。

enter image description here

翻转将悬停附加到非悬停状态,但是下次您悬停时,src现在具有`xxx-1-hover-hover.jpg

任何帮助将不胜感激!

0 个答案:

没有答案