我在div中放了一张图片.当我将鼠标移到div中时,图像应该每秒减少5%.我已经完成了这个 playbook ,但什么都没有发生.

document.addEventListener("DOMContentLoaded", (event) => {
  const element = document.getElementsByTagName("footer")[0];
  const div = element.getElementsByTagName("div")[0];
  var urlImg = "https://www.coding-academy.fr/wp-content/uploads/2017/10/CODING_LOGO_CMJN.png";

  var imagejavascript = document.createElement("img");
  imagejavascript.src = urlImg;
  imagejavascript.style.width = "100%";
  imagejavascript.style.height = "100%";
  div.appendChild(imagejavascript);

  const img = div.getElementsByTagName("img")[0];
  var isOnDiv = false;
  var currentHeight = 100;

  div.addEventListener("mouseenter", function() {
    if (isOnDiv) return;
    isOnDiv = true;

    var intervalId = setInterval(function() {
      currentHeight -= 5;
      img.style.height = currentHeight + "%";

      if (currentHeight <= 0) {
        clearInterval(intervalId);
        setTimeout(function() {
          isOnDiv = false;
          currentHeight = 100;
          img.style.height = "100%";
        }, 1000);
      }
    }, 1000);
  });

  div.addEventListener("click", function() {
    div.removeChild(img);
  });
});
<footer>
  <div></div>
</footer>

我正在试图找到一种方法来减少图像大小的5%,每一秒我进入div的鼠标.

推荐答案

这里有几个问题:

  • 您将img中的heightwidth都设置为100%.更改其中的一个将不会产生任何影响.您需要设置其中一个值,并在更改该属性值时动态zoom 图像.
  • 不要使用变量(即isOnDiv)以保持悬停状态.使用单独的mouseentermouseleave事件处理程序分别开始和结束间隔.

下面是一个包含上述更改的工作示例:

document.addEventListener("DOMContentLoaded", (event) => {
  const element = document.querySelector("footer");
  const div = element.querySelector("div");
  
  const img = document.createElement("img");
  img.src = "https://www.coding-academy.fr/wp-content/uploads/2017/10/CODING_LOGO_CMJN.png";
  img.style.width = "100%";
  div.appendChild(img);

  let currentWidth = 100;
  let intervalId;
  
  const setImgSize = value => img.style.width = value + "%";

  div.addEventListener("mouseenter", () => {
    intervalId = setInterval(function() {
      currentWidth -= 5;
      setImgSize(currentWidth);
      
      if (currentWidth <= 0) {
        clearInterval(intervalId);
      }
    }, 1000);
  });
  
  div.addEventListener('mouseleave', () => {
    clearInterval(intervalId);
    currentWidth = 100;
    setImgSize(currentWidth);
  }); 

  div.addEventListener("click", function() {
    clearInterval(intervalId);
    div.removeChild(img);
  });
});
<footer>
  <div></div>
</footer>

Javascript相关问答推荐

如何在NightWatch.js测试中允许浏览器权限?

如何提取Cypress中文本

使用JavaScript单击上一个或下一个特定按钮创建卡滑动器以滑动单个卡

是否有方法在OpenWeatherMap API中获取过go 的降水数据?

如何使用侧边滚动按钮具体滚动每4个格?

如何才能拥有在jQuery终端中执行命令的链接?

构造HTML表单以使用表单数据创建对象数组

无法访问Vue 3深度监视器中对象数组的特定对象值'

如何在bslib nav_insert之后更改导航标签的CSS类和样式?

并不是所有的iframe都被更换

制作钢琴模拟器,并且在控制台中不会执行或显示该脚本

如何从HTML对话框中检索单选项组的值?

我在Django中的视图中遇到多值键错误

如何在尚未创建的鼠标悬停事件上访问和着色div?

react 路由如何使用从加载器返回的数据

如何在Jest中模拟函数

如何在加载页面时使锚定标记成为焦点

如何阻止外部脚本进入顶层导航

不允许在对象文本中注释掉的属性

Playwright:ReferenceError:browserContext未定义