在jquery中创建和分配一个css类

Creating & Assigning a css class in jquery

本文关键字:一个 css jquery 创建 分配      更新时间:2023-09-26
//Dynamically getting the windows width
var windowwidth = $(window).width() - 50;
//dynamically assigning the windowwidth value to the class(dynamically)
$(window).load(function () {
    $('.cntnt').css('width', windowwidth + 'px');
})

$("#menu-toggle").click(function(e) {
    e.preventDefault();
    $('.wrapper-content').toggleClass('cntnt');
});
#wrapper {
    padding-left: 0;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}
#wrapper.toggled {
    padding-left: 250px;
}
#sidebar-wrapper {
    z-index: 1000;
    position: fixed;
    left: 250px;
    width: 0;
    height: 100%;
    margin-left: -250px;
    overflow-y: auto;
    background: #4a4f55;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}
#wrapper.toggled #sidebar-wrapper {
    width: 250px;
}
#page-content-wrapper {
    width: 100%;
    position: absolute;
    padding: 15px;
}
#wrapper.toggled #page-content-wrapper {
    position: absolute;
    margin-right: -250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
<div class="wrapper-content">
  <div class="container-fluid">
    <a href="#menu-toggle" class="btn pull-left" id="menu-toggle" >
      toggle menu
    </a>
    <div class="row">
      <div class="col-lg-12">
        <h1>Simple Sidebar</h1>
        <p>This template has a responsive menu toggling system. The menu will appear collapsed on smaller screens, and will appear non-collapsed on larger screens. When toggled using the button below, the menu will appear/disappear. On small screens, the page content will be pushed off canvas.</p>
        <p>Make sure to keep all page content within the <code>#page-content-wrapper</code>.</p>
      </div>
    </div>
  </div>
</div>

嗨,我试图在jQuery中创建一个css类并将其分配给jQuery中的另一个id。主要议程是,我想在 jQuery 中切换类,它的宽度为 $(窗口(,单击一个函数,该类应该切换到 id,

这是我实现的代码,我没有错误,但也没有输出。请帮帮我。

$(window).load(function () {
    $('.cntnt').css('width', + windowwidth + 'px');
})

这不是类分配,你只是找到这个类的元素并设置它们的样式。

如果你想动态设置类,你应该创建新的样式元素,如下所示:

$(window).load(function () {
    $('body').prepend('<style>.cntnt { width:' + windowwidth + 'px }</style>')
})

为了动态创建 css 类,您可以创建一个 <style> 元素并将其附加到 <head>

$("<style>")
  .prop("type", "text/css")
  .html(".cntnt { width: " + windowwidth + "px; }")
  .appendTo("head");

或者,如果你只需要 windowidth,你可以简单地在静态 css 中创建一个带有 vwcalc 的类。哪个100vw等于$(window).width()calc计算不同单位之间的值。通过这种方式,您可以在用户调整窗口大小时动态重新计算宽度。使用 javascript,您需要将代码放入事件$(window).resize才能执行此操作。

.cntnt {
  width: calc(100vw - 50px);
}