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

时间:2015-04-08 18:51:46

标签: javascript jquery css

我在页面上有响应元素的外部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替换图像的解决方案,例如:Using jQuery to change image src when browser is resized

但我不确定这个例子,如何包含悬停图像,以及CSS文件中的其他属性,如float,width,margin。

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

1 个答案:

答案 0 :(得分:0)

这方面的一般方法需要有以下几点:

一个事件监听器使用$(window).resize() which can then adjust the CSS using $('#some-element-id')。css('property-name','value')`和图像源(你说你已经知道如何取决于

的条件
if($(window).width() < x){
...

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

好吗?