gpt4 book ai didi

javascript - 根据类设置元素宽度

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

我正在尝试使用 jQuery 根据单独的 div 类设置图像的宽度。我以为我可以使用 if 语句,但它不起作用。

$(document).ready(function() {
if ($('#map-container').hasClass('zoom-100, zoom-130, zoom-150')) {
$('#marker').css("width", 70);
} else if ($('#map-container').hasClass('zoom-70, zoom-80')) {
$('#marker').css("width", 40);
} else {
$('#marker').css("width", 25);
}
});

最佳答案

如果#marker 是#map-container 的,则不需要jquery - 只需使用css 并相应地定位div。先设置base size,再根据parents classes设置size。

 #marker {
width: 25px;
}

#map-container.zoom-70 #marker,
#map-container.zoom-80 #marker {
width: 40px;
}

#map-container.zoom-100 #marker,
#map-container.zoom-130 #marker,
#map-container.zoom-150 #marker {
width: 70px;
}

如果#marker 是#map-container 的兄弟,您仍然不需要jquery - 只需使用css 并通过通用兄弟组合器 定位div “~”。先设置base size,再根据sibling classes设置size。

 #marker {
width: 25px;
}

#map-container.zoom-70 ~ #marker,
#map-container.zoom-80 ~ #marker {
width: 40px;
}

#map-container.zoom-100 ~ #marker,
#map-container.zoom-130 ~ #marker,
#map-container.zoom-150 ~ #marker {
width: 70px;
}

如果您绝对肯定必须使用 jquery - 那么您可以使用 switch 语句,它总是比多个 if 语句更好。

请注意,多个语句可以一起阻塞,如果前面的语句都不为真,则默认语句出现。

以下代码片段演示了不同的 switch 语句;

updateDiv();


$('#class-selector').change(function(){
document.querySelector('#map-container').className = 'zoom-' + $(this).val();
updateDiv();
})

function updateDiv() {
switch(true) {
case $('#map-container').hasClass('zoom-150'):
case $('#map-container').hasClass('zoom-130'):
case $('#map-container').hasClass('zoom-100'):
$('#marker').css("width", 70).text('70px');
break;

case $('#map-container').hasClass('zoom-80'):
case $('#map-container').hasClass('zoom-70'):
$('#marker').css("width", 40).text('40px');
break;

default:
$('#marker').css("width", 25).text('25');
}
}
#map-container {
border: solid 1px red;
padding: 15px;
}

#marker {
background: blue;
color: white;
text-align: center
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="map-container" class="zoom-100">
<p>This div with the red border is #map-container and the the following blue div is #marker. Changing the select list below will apply the different class to #map-container and will change the blue div accordingly.</p>

<label>Select a different size to apply to the div</label>
<select id="class-selector">
<option value="">None</option>
<option value="70">zoom-70</option>
<option value="80">zoom-80</option>
<option value="100" selected>zoom-100</option>
<option value="130">zoom-130</option>
<option value="150">zoom-150</option>
</select>

<hr/>



<div id="marker"></div>
</div>

关于javascript - 根据类设置元素宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53006500/

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