【问题标题】:decrease width of a div by a random number on button click单击按钮时通过随机数减小 div 的宽度
【发布时间】:2020-12-20 20:49:51
【问题描述】:

这是我的代码,我想在任何时候点击带有随机数的按钮来减小 div 的宽度

let humanDiv = document.getElementById("humanDiv");
let monsterDiv = document.getElementById("monsterDiv");

function attBtn() {
let numRandom = Math.floor(Math.random() * 40) + 1;
humanDiv.style.width -= numRandom + 'px';
monsterDiv.style.width -= numRandom + 'px';
}

【问题讨论】:

  • 什么不起作用?
  • 你为什么使用 Javascript 而不是 CSS?让你的代码成为一个 sn-p。

标签: javascript html css


【解决方案1】:

object.style.width 给你一个你不能在上面使用-= 的字符串。

试试:

humanDiv.style.width = parseInt(humanDiv.style.width)+ numRandom + 'px';
monsterDiv.style.width = parseInt(monsterDiv.style.width) + numRandom + 'px';

【讨论】:

    【解决方案2】:

    humanDiv.style.width 属性返回最后带有像素的字符串,因此在减少它之前,您应该将此属性转换为数字。

    <script>
      let humanDiv = document.getElementById("humanDiv");
      let monsterDiv = document.getElementById("monsterDiv");
    
      function attBtn() {
        let numRandom = Math.floor(Math.random() * 40) + 1;
        let humanDivWidth = new Number(humanDiv.style.width.slice(0, -2));
        let monsterDivWidth = new Number(humanDiv.style.width.slice(0, -2));
        humanDiv.style.width = humanDivWidth - numRandom + "px";
        monsterDiv.style.width = monsterDivWidth - numRandom + "px";
      }
    </script>
    

    【讨论】:

      【解决方案3】:

      如果之前没有设置元素的宽度,则无法访问:

       console.log(humanDiv.style.width);
      
      // will give 
      //
      // (nothing)
      

      所以用随机数减去任何东西是没有意义的。

      CSS 转换可能会帮助您: CSS Transform with element resizing.

      【讨论】:

        猜你喜欢
        • 2013-12-31
        • 2015-05-09
        • 1970-01-01
        • 1970-01-01
        • 2023-01-23
        • 2012-12-17
        • 1970-01-01
        • 1970-01-01
        • 2021-05-15
        相关资源
        最近更新 更多