javascript - 如何更改背景图片onClick

标签 javascript jquery html css

我需要实现 onClick更改背景图片: 存在多个与类同名的元素

.click{
    background-image: url("http://icons.iconarchive.com/icons/graphicloads/100-flat/256/phone-icon.png");
    }
<a class='click' onclick="$(this).css('background-image','http://previews.123rf.com/images/runlenarun/runlenarun1411/runlenarun141100068/33499512-Single-flat-icon-with-long-shadow-for-web-applications-email-icons-design-Envelope-with-close-sign-V-Stock-Vector.jpg');"></a>
<a class='click' onclick="$(this).css('background-image','http://previews.123rf.com/images/runlenarun/runlenarun1411/runlenarun141100068/33499512-Single-flat-icon-with-long-shadow-for-web-applications-email-icons-design-Envelope-with-close-sign-V-Stock-Vector.jpg');"></a>
<a class='click' onclick="$(this).css('background-image','http://previews.123rf.com/images/runlenarun/runlenarun1411/runlenarun141100068/33499512-Single-flat-icon-with-long-shadow-for-web-applications-email-icons-design-Envelope-with-close-sign-V-Stock-Vector.jpg');"></a>

当我点击任何 <a>标记,图像更改为任何其他图像 onClick。元素 id不能用。只有类(Class)。请帮忙

Fiddle

最佳答案

$(document).ready(function(){
  $('.click').click(function(){
    var img= $(this).data('img');
    $(this).css('background-image','url("'+img+'")');
  });
});
.click{
    background-image: url("http://icons.iconarchive.com/icons/graphicloads/100-flat/256/phone-icon.png");
  height:100px;
  width:200px;
  display:inline-block;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class='click' data-img="http://previews.123rf.com/images/runlenarun/runlenarun1411/runlenarun141100068/33499512-Single-flat-icon-with-long-shadow-for-web-applications-email-icons-design-Envelope-with-close-sign-V-Stock-Vector.jpg"></a>
<a class='click' data-img='http://previews.123rf.com/images/runlenarun/runlenarun1411/runlenarun141100068/33499512-Single-flat-icon-with-long-shadow-for-web-applications-email-icons-design-Envelope-with-close-sign-V-Stock-Vector.jpg'></a>
<a class='click' data-img='http://previews.123rf.com/images/runlenarun/runlenarun1411/runlenarun141100068/33499512-Single-flat-icon-with-long-shadow-for-web-applications-email-icons-design-Envelope-with-close-sign-V-Stock-Vector.jpg'></a>

检查这个。我为你创建了一个例子。 :)

关于javascript - 如何更改背景图片onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38656167/

相关文章:

javascript - 无法在 HTML 页面上查看 JavaScript 函数的结果

javascript - IE 7/8 绝对定位元素不能下降超过某个点 JS/Jquery

jquery - 如何找出第一个子标签名称是什么?

java - Struts 2转义html不起作用?

html - 将 child 放在父元素的中心

php - 显示带有数据库选择内容的警报

javascript - Three.js 创建多个对象

javascript - 更改轮播导航点击上的背景图像

javascript - 谷歌线图 - 设置较小的幅度

html - 使用 Bootstrap 更改导航栏的字体颜色