javascript onClick change background picture of div

对着背影说爱祢 提交于 2019-12-25 01:37:20

问题


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

First I wrote this:

<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>

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;'}

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>

Are there any suggestions?


回答1:


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)');
})

See this Fiddle.




回答2:


Try this:

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

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

You needed to pass a string to the showP function in the onclick handler, which should be in quotes. You're passing a string into the function, which is in the pic variable being passed into the function. You want that string variable's value to be concatenated with the URL rule for the background style.




回答3:


the background image URL does not require quotes. Try:

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



回答4:


As others have said, you do seem to have an issue with quotes. You can check out my working example on jsFiddle.



来源:https://stackoverflow.com/questions/8732523/javascript-onclick-change-background-picture-of-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!