【问题标题】:I dont know whats wrong with this simple javascript code, I have checked this over and over again but does not work我不知道这个简单的 javascript 代码有什么问题,我一遍又一遍地检查了这个但不起作用
【发布时间】:2021-05-21 08:37:30
【问题描述】:

鼠标悬停时展开的简单图像,鼠标悬停时相反,我一遍又一遍地检查代码,在每一行放置警报消息以查看其是否有效,警报消息一直有效,但对图像没有影响.我很困惑,我不知道怎么了。

var side = 200;
var a = 20;
var t = 0;


function expand() {
  console.log("expand is ok");
  clearInterval(t);
  t = setInterval(grow, 20);

}

function grow() {
   console.log("Entered grow");
  if (side < 300) {
    console.log("entered if loop");
    side = side + a;
    document.getElementById("new").style.width = side;
    console.log("After statement")
  } else
    clearInterval(t);
  console.log("clear")
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Zoom in Zoom out</title>
</head>

<body>
  <img src="../images/women.jpg" id="new" alt="Women" onmouseover="expand()" width=2 00px>
</body>

</html>

【问题讨论】:

  • 尝试删除(格式错误的)width=2 00px 属性...
  • 另外:你实际上并不需要 JavaScript;一个 CSS img {transition: width 1s; } img:hover { width: 300px; } 就足够了...
  • @AKX 我不知道 2 00px 是如何在复制粘贴中分离的,在我的代码中是正常的。我是 javascript 新手,只是练习事件和函数。我知道这可以在 css 中完成,但不是每次转换 20 毫秒,这在 atm 中并不重要,但我正在练习,正如我之前所说的。
  • 您可能已经看到所有警报框都被激活到最后,我不明白为什么 get element by id 。风格 。宽度不起作用,边正在增加,因为它应该是......
  • 试试.width = '' + side + 'px'(或等效的模板字符串)——CSS 样式有单位...

标签: javascript function events


【解决方案1】:

扩展我的评论:

问题是您试图将原始数字(例如 200)分配给宽度 CSS 属性。

如果您查看 CSS,您会将“200 像素”拼写为

foo {
  width: 200px;
}

因此,您需要为动态操作赋予一个单位(此处为像素):

foo.style.width = `${width}px`;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2013-02-04
    • 2021-03-11
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多