繁体   English   中英

根据屏幕宽度使用Jquery修改CSS宽度

[英]Modifying CSS width with Jquery according to screen width

嘿伙计我用以下代码遇到了一些问题。 我想要做的是根据屏幕的宽度通过css修改div的宽度。

<html>
<head>
     <script src="../jquery/jquery.js" type="text/javascript"> // Add JQuery Code.   </script>
</head>
<body>
<div id="something" style="background-color: black; width: 100px;">hello</div>
<script>
$(document).ready(function() {
    if (screen.width = 1024) {
        $(#something).css('width':'200px', 'background-color':'blue');
    }
    elseif (screen.width = 1366) {
        $(#something).css('width':'300px', 'background-color':'blue');
    }
}
</script>
</body>

你有一些问题。 应使用范围检查宽度

$(document).ready(function() {
  if ($(window).width() >= 1366) {
    $('#something').css({ 'width':'300px', 'background-color':'blue' });
  } else if ($(window).width() >= 1024) {
    $('#something').css({ 'width':'200px', 'background-color':'blue' });
  }
});

编辑:结合window.resize,然后我认为它的行为正是你想要的。 但您也可以考虑使用css媒体查询来实现响应式布局。

@media only screen and (min-width:1024px){
    .my-style {
        background-color: blue;
        width: 200px;
    }
}
@media only screen and (min-width:1366px){
    .my-style {
        background-color: blue;
        width: 300px;
    }
}

尝试使用窗口的resize事件,就像在if语句中分配值一样,

$(document).ready(function() {
  $(window).resize(function(){
    var something = $('#something');
    if ($(this).width() >= 1366) {
        something .css({'width':'200px', 'background-color':'blue'});
    }
    else if ($(this).width() >= 1024) {
        something.css({'width':'300px', 'background-color':'blue'});
    }
  });
});

注意:您的代码有很多语法错误,例如将未定义的var作为选择器传递, 如果等等传递错误,以及我收到了一个downvote。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM