在桌面尺寸上,我的导航栏品牌仅包含一张较大的图像。但在移动设备尺寸上,我希望将较大的图像替换为两个较小的图像。为此,我使用了 jQuery,当我在移动设备上检查它时,它看起来正是我想要的。但问题是,当我更改浏览器的大小时,图像不会被实时替换。有什么办法可以实现这个目标吗?
$(document).ready(function() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="assets/images/Llogo AIP.png"><img src="assets/images/CoA RKS.png">');
}
});
<a class="navbar-brand" href="index.html"><img src="assets/images/logo.png"></a>
最佳答案
要获取在调整窗口大小时执行的代码,您应该使用 .resize()
:
The resize event is sent to the window element when the size of the browser window changes.
$(window).resize(function() {....
演示:
$(document).ready(function() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="https://homepages.cae.wisc.edu/~ece533/images/pool.png"><img src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png">');
}
$(window).resize(function() {
if ($(window).width() < 575.98) {
$('.navbar-brand').children().remove();
$('.navbar-brand').append('<img src="https://homepages.cae.wisc.edu/~ece533/images/pool.png"/><img src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png"/>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="navbar-brand" href="index.html"><img src="assets/images/logo.png"></a>
关于javascript - 使用 jQuery 实时更新 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59982326/