简体   繁体   中英

onMouseOver change background image position

I'm trying to reposition the background image of a div using javascript. Here's what I have but it doesn't seem to work. What am I missing?

<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition="0px 150px"">link one</a>
<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition="0px 350px"">link two</a>

<div id="rubbish_image"></a>

I'm not entirely sure, but there's two obvious problems I can see with your JavaScript:

  1. You've got two " just before the closing > of the a tags, as a result of
  2. Your use of " inside of the string, which isn't allowed (you can use ' inside a string delimited with " , or vice versa, but " inside of a string delimited by " terminates the string).

I'd suggest, therefore, amending the code to:

<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition='0px 150px';">link one</a>
<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition='0px 350px';">link two</a>

I don't believe it's a huge problem, but you also didn't terminate your JavaScript within the onmouseover attribute, so I also added the ; to the end of each.

You're nesting double quotes, which won't work.

A simple fix is to only use single quotes inside the onmouseover attributes:

<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition='0px 150px'">link one</a>
<a href="#" onMouseOver="document.getElementById('rubbish_image').style.backgroundPosition='0px 350px'">link two</a>

<div id="rubbish_image"></a>

You're already doing this inside getElementById .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM