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