jQuery:当屏幕大小改变时,如何更改默认图像和悬停图像

jQuery: how to change default image and hover image when screen size is changed

本文关键字:图像 何更改 默认 悬停 屏幕 改变 jQuery      更新时间:2023-09-26

我在页面上有一个用于响应元素的外部CSS文件:

@media only screen and (max-width:1089px){
   #shipping a{float:left;width:100%;margin-top:7px;padding:10px 0 10px 0;background:url("/images/shared/resp1.png") no-repeat;}
   #shipping a:hover{float:left;margin-top:7px;padding:10px 0 10px 0;background:url("/images/shared/h-resp1.png") no-repeat;}
}
@media only screen and (max-width:1011px){
   #shipping a{float:left;width:100%;margin-top:7px;padding:10px 0 10px 0;background:url("/images/shared/resp2.png") no-repeat;}
   #shipping a:hover{float:left;margin-top:7px;padding:10px 0 10px 0;background:url("/images/shared/h-resp2.png") no-repeat;}
}

我需要删除外部CSS文件,并使用jQuery来替换图像。

我已经找到了使用jQuery替换其他用户发布的图像的解决方案,比如:当浏览器调整大小时,使用jQuery更改图像src

但我不确定下面的例子,如何也包括悬停图像,以及CSS文件中的其他属性,如float、width、margin。

如何使用jQuery替换默认图像、悬停图像以及其他CSS属性?

这方面的一般方法需要遵循以下内容:

使用$(window).resize() which can then adjust the CSS using$('#some element id').css('property-name','value')'和图像源的事件侦听器(您说您已经知道如何根据沿线的条件进行操作

if($(window).width() < x){
...

关于悬停功能,如果您计划使用JQuery执行此操作,请考虑使用一个变量来存储悬停图像的路径,该路径可以在上面的resize事件侦听器中更新,然后使用与更改图像的主源时相同的代码为图像上的悬停事件创建一个事件侦听器,但仅引用您创建的变量。

好吗?