Javascript 使用javascript更改悬停时的背景图像位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4583196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:04:42  来源:igfitidea点击:

Changing background image position on hover using javascript

javascriptcss

提问by rdp

I have 10 links. I am using a separate sprite sheet for a single link which consist of active, hover and inactive link image. I want to know how can i change the background-postion from javascript. I know how to do this in css but for 10 different links i think javascript will a better option as i can use the same code for every link. Waiting for your suggestions.

我有10个链接。我为单个链接使用单独的精灵表,该链接由活动、悬停和非活动链接图像组成。我想知道如何从 javascript 更改背景位置。我知道如何在 css 中执行此操作,但是对于 10 个不同的链接,我认为 javascript 将是更好的选择,因为我可以对每个链接使用相同的代码。等待您的建议。

回答by pixeline

you are mistaken: this should be done in CSS, its the fastest to render, even though it takes more initial declarations. Just make sure your CSS is optimized.

你错了:这应该在 CSS 中完成,它渲染速度最快,即使它需要更多的初始声明。只要确保您的 CSS 已优化。

.links{
background:transparent url(sprite.png) 0 0;
}

#link1{
background-position: 0 0;
}
#link1:hover{
background-position: 0 -50px;
}

#link2{
background-position: 100px 0;
}
#link2:hover{
background-position: 100px -50px;
}

And the HTML:

和 HTML:

<a class="links" id="link1" href="#">link 1</a>
<a class="links" id="link2" href="#">link 2</a>

If you really, really want to do it in javascript, you're looking for the style() method. See W3Schools on style() and backgroundPosition

如果你真的,真的想用 javascript 来做,你正在寻找 style() 方法。请参阅 W3Schools 上的 style() 和 backgroundPosition

回答by Gabriele Petrioli

The best is to use css, even for multiple images.

最好是使用 css,即使是多个图像。

If the sizing is the same for the sprites of the 10 links, you can make a rule that is agnostic of the image and just repositions the background image

如果 10 个链接的精灵的大小相同,您可以制定一个与图像无关的规则,只需重新定位背景图像

a.someclass:hover{
  background-position:Xpx Ypx;
}

and apply the someclass(or whatever you name it) to all your links...

并将someclass或任何您命名的)应用于您的所有链接...