gpt4 book ai didi

javascript - 根据屏幕宽度用Jquery修改CSS宽度

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:54 25 4
gpt4 key购买 nike

大家好,我在使用以下代码时遇到了一些问题。我想做的是根据屏幕的宽度通过 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 query来实现响应式布局。

@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;
}
}

关于javascript - 根据屏幕宽度用Jquery修改CSS宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23190948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com