使用 Javascript 更改背景位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15066465/
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-10-26 23:21:25  来源:igfitidea点击:

Changing background position with Javascript?

javascripthtmlcssimagecss-sprites

提问by Matt104

Though I can see this question has been asked before I really need a solution without the use of JQuery, its for an embedded web interface and I don't want the overhead of loading jQuery. I need to be able to manipulate sprites using just the JS on the single page, the state of the sprite is dependent on certain JS variables. I'm sure this must be possible, but can't find anything without the use of JQuery.

尽管在我真正需要不使用 JQuery 的解决方案之前,我可以看到有人问过这个问题,但它用于嵌入式 Web 界面,我不想要加载 jQuery 的开销。我需要能够在单个页面上仅使用 JS 来操作精灵,精灵的状态取决于某些 JS 变量。我确信这一定是可能的,但如果不使用 JQuery,就找不到任何东西。

回答by Mujtaba Hassan

The easiest way (I think) is to define your own css classes and change those clasess on certan events. i.e.

最简单的方法(我认为)是定义自己的 css 类并在 certan 事件上更改这些类。IE

<style type="text/css">
.bg1{
/* Some attributes set here */
background-position:cen??ter;
}
.bg2{
/* Some attributes set here */
background-position:left;
}

</style>

and then you put your javascript like this

然后你把你的javascript像这样

document.getElementById("some_id").class = "bg2";

回答by Forhad

I think you can use Object.style.backgroundPosition="position" to change your desired background position .

我认为你可以使用 Object.style.backgroundPosition="position" 来改变你想要的背景位置。

Try this code

试试这个代码

 <!DOCTYPE html>
<html>
<head>
<style>
div
{
background-image: url('example.png');
background-repeat: no-repeat;
width: 400px;
height: 400px;
border: 1px solid #000000;
}
</style>
<script>
function displayResult()
{
document.getElementById("div1").style.backgroundPosition="center bottom";  
}
</script>
</head>
<body>

<button type="button" onclick="displayResult()">Position background image</button>
<br>
<div id="div1">
</div>

</body>
</html>

Reference

参考