javascript onClick更改div的背景图片 [英] javascript onClick change background picture of div

查看:488
本文介绍了javascript onClick更改div的背景图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的最终目标是通过点击sampla图片来改变div的背景。

My ultimate goal is to change the background of a div through clicking on the sampla picture.

首先我写了这个:

<a onclick="document.getElementById('sp').style.background="url('/assets/castle.png')"">...<a>

但它不起作用。我注意到问题是使用了多个和。所以把函数放到脚本标签中:

but it didn't work. I noticed that the problem was usage of multiple " and '. So put the function into a script tag:

<script type="text/javascript">
    var pic="";
    function showP(pic) { document.getElementById('sp').style.background='url(pic)';};
</script>

<a onclick="showP(/assets/castle.png)"><img src="/assets/castle.png" width="50px" height="50px"></a>

正如看到/资产所假设的那样dir,这是一个rails应用程序。我也尝试使用jQuery选择器,如$(#sp)。css()或完全删除变量并尝试以下函数:

As supposed by seeing /assets dir, this is a rails app. I also tried o use jQuery selectors like $("#sp").css() or dropping the variable altogether and trying the function as:

function showp1() { document.getElementById('sp').style.cssText='background: transparent url(/assets/castle.png) no-repeat 0 0;'}

尝试在类似标题的问题中提出的解决方案,但没有一个确实有效。无论我尝试什么,在html源代码,部分 showP(/ assets / cas tle.png)下面标记为红色:

to try out solutions proposed in questions with similar titles but none did work. Whatever I try, on the html source, the portion showP(/assets/castle.png)" below is marked red:

<a onclick="showP(/assets/castle.png)"><img src="/assets/castle.png" width="50px" height="50px"></a>

有什么建议吗?

推荐答案

避免将JS放入HTML代码中。使用不显眼的事件监听器。它们在jQuery中非常简单:

Avoid putting JS in your HTML code. Use unobtrusive event listeners. They are very easy in jQuery:

$('#clickMe').on('click', function() {
    $('#changeMe').css('background-image', 'url(http://placehold.it/200x200/ff0000)');
})

看到这个小提琴。

这篇关于javascript onClick更改div的背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆