【问题标题】:Changing a css class from javascript [duplicate]从javascript更改css类[重复]
【发布时间】:2018-12-11 16:31:31
【问题描述】:

我想将一个元素的height 设置为window.innerheight,但我必须在CSS 中进行设置,因为不知何故我无法访问该元素来使用javascript 来更改它的样式。 有没有办法做到这一点?喜欢在 javascript 中更改 CSS 类?

我试过了:

document.getElementById('root').style.setProperty('--view-height', window.innerHeight +'px');

在 CSS 中:

.menu {
    height: var(--view-height) !important;
}

它可以工作,但旧版浏览器不支持CSS Variables,所以我不能使用它,但我想要类似的东西。

编辑: 有很多答案,但他们都使用 javascript,我说我不能使用 js 来设置元素样式!我只想通过 css 类样式来做到这一点

【问题讨论】:

  • 也许 polyfill 可以帮助您解决旧的浏览器问题?
  • 有了这个,你可以添加一个类名,并在你的 CSS 中为这个新的类名设置样式。 w3schools.com/howto/howto_js_add_class.asp
  • 如何在 css 中将样式设置为 window.innerheight? !!

标签: javascript css sass


【解决方案1】:

在现代浏览器中,您可以使用:

document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyOtherClass');

虽然,为了完成您的具体案例,我会选择לבני מלכה 的答案。

【讨论】:

    【解决方案2】:

    也许改用适当的 CSS:

    window.innerHeight +'px' 的结果与使用 100vh 的高度相同。单位vh 表示“视口高度”,100vh 是内窗口的全高。

    见:https://developer.mozilla.org/en-US/docs/Web/CSS/length#Viewport-percentage_lengths

    【讨论】:

    【解决方案3】:

    在 javascript 中设置height 而不是使用variables

    document.getElementById('root').style.height=window.innerHeight +'px';
    

    参见示例:

     document.getElementById('root').style.height=window.innerHeight +'px';
    #root{
    background-color:red;
    }
    <div id="root"></div>

    对你的编辑没有用的 js 使用 height:100vh;

    #root{
    height:100vh;
    background-color:red;
    }
    <div id="root"></div>

    【讨论】:

    • 嘿..这是你要找的吗?
    • 查看我的编辑请使用css而不是js
    • no 100 vh IOS 设备有问题:
    • 你必须使用 js 可能只有在你在移动尺寸屏幕上才使用 js
    【解决方案4】:

    使用vh 单元是正确的方法。(尽管 Mahboobeh Mohammadi 说它与 ios 不兼容) height: 100vh; 是视图的全高..

    【讨论】:

      【解决方案5】:

      对于普通的 Js

      function addClassById (_id,_class) {
        document.getElementById(_id).classList.add(_class);
      }
      
      function removeClassById (_id,_class) {
        document.getElementById(_id).classList.remove(_class);
      }
      
      addClassById("root","newClass")
      

      我建议您使用 JQUERY,它非常易于使用。 把这个cdn链接放在你的head标签上然后使用它。

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      
      //This is for change css
      $("#root").css({
      "background-color": "yellow", 
      "font-size": "200%"
      });
      
      
      
       // This is how to add class
      $("#root").addClass('newClass');
      
      
      
      
      
      // This is how to remove class
       $("#root").removeClass('newClass')
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-22
        • 2014-10-12
        • 1970-01-01
        • 2020-07-09
        • 2018-04-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多