【问题标题】:Change style with Javascript使用 Javascript 更改样式
【发布时间】:2023-03-15 23:54:01
【问题描述】:
<html>
  <head>
    <style>
      #line {
        height: 1px;
        width: 100%;
        float: left;
        background-color: #8e9194;
        position: absolute;
        top: 85%;
        left: 0;
      }
    </style>
  </head>
  <body>
    <button id="b1">Click Here</button>
    <script>
      var o = document.getElementById("line");
      document.getElementById("b1").onmouseover = function () {
        o.style.height = "10px";
      };
      document.getElementById("b1").onmouseout = function () {
        o.style.height = "1px";
      };
    </script>
    <div id="line"></div>
  </body>
</html>

无法让此代码工作。我要做的就是在鼠标悬停时增加线条的大小,并在鼠标移出时将其恢复为 1px。

如果有任何方法可以在其中加入一些动画,那也很好。

谢谢。

【问题讨论】:

  • 如果你可以使用jQuery,我强烈推荐它。如果没有,请发表评论,我可以帮助您使用纯 JavaScript 制作动画。

标签: javascript css height onmouseover onmouseout


【解决方案1】:

如果您还需要添加一些动画,我建议使用jQuery。它既快速又简单:

$(function() {
    $("#b1").hover(function() {
        $("#line").stop().animate({ height: 10 }, 1000);
    }, function() {
        $("#line").stop().animate({ height: 1 }, 1000);
    });
});

演示: http://jsfiddle.net/8YsSd/

【讨论】:

    【解决方案2】:

    您需要将 JavaScript 放在您所指的元素之后:

    <button id="b1">Click Here</button>
    <div id="line"></div>
    
    <script> var o = document.getElementById("line");
    document.getElementById("b1").onmouseover = function ()
    {o.style.height="10px";}; document.getElementById("b1").onmouseout =
    function () {o.style.height="1px";}; 
    </script>
    

    您的行 var o = document.getElementById("line"); 在元素实际存在之前执行。

    jsFiddle example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多