Body OnClick doesn't work… but the onclick works when attached to a <a> tag?

℡╲_俬逩灬. 提交于 2020-01-25 12:33:25

问题


I have the following Onclick event

onClick="document.body.style.background = 'url(galleries/g2.jpg)'"

and when i attach it to

<a onClick="document.body.style.background = 'url(galleries/g2.jpg)'"> blah</a>

all works fine. but I want it as a body onclick event as follows

<body class="g" onClick="document.body.style.background = 'url(galleries/g2.jpg)'">

and i get no dice.

The only thing to note would be that the class "g" already has a background image specified, but I don't think that should matter.


回答1:


Use this. like this

<body onClick="this.style.background = 'url(http://placehold.it/20x50)';">

JSFiddle of the code above jsfiddle.net/mrRRG/2/. But please do not use this type of code construction. It's better to make few CSS classes and use javascript to change them on event fire



来源:https://stackoverflow.com/questions/9152802/body-onclick-doesnt-work-but-the-onclick-works-when-attached-to-a-a-tag

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