gpt4 book ai didi

jquery - 使用 jquery 添加 css 属性

转载 作者:行者123 更新时间:2023-12-01 06:55:18 25 4
gpt4 key购买 nike

我的 html 中有一张图像,并且有 5 个不同的链接,我想仅使用一个类更改图像背景位置,因此我在函数中设置了参数,但它不起作用?

<head>

<script type="text/javascript" src="jquery-1.7.min.js"></script>

<script type="text/javascript">

$(function Bg(left,top) {

$('.me').each(function (){
$(this).hover(function(){
$('.container').css({backgroundPosition: left+ 'px', top + "px"})

})

})

})




</script>
<style>

.container { width:100px; height:100px; float:left; background:url(../bike.jpg) left top no-repeat;}
</style>

</head>

<body>
<a href="#" class="me" onmouseover="Bg(50,60)">click me1</a>
<a href="#" onmouseover="Bg(80,70)" class="me">click me2</a>
<a href="#" onmouseover="Bg(120,60)" class="me">click me3</a>
<a href="#" onmouseover="Bg(150,60)" class="me">click me4</a>

<div class="container"></div>

</body>

最佳答案

background-position 的语法(意外的 ,) 是错误的。尝试一下

$('.container').css('background-position', left + 'px ' + top + 'px');

$('.container').css({backgroundPosition: left + 'px ' + top + 'px'});

相反。

编辑:这不是 .hover() 的工作原理。要么使用 .hover 要么 mouseover,混合使用它们不是一个好主意。您可以使用以下代码来解决您的问题,但是,我建议您查看 jQuery 文档。尝试分离您的 JavaScript 逻辑,尽可能不要使用属性处理程序。

JSFiddle Demo

$(function(){
/* The following function will reset the background-position
* if the mouse moves out of the given element
*/
$('.me').mouseout(function(){
$('.container').css('background-position', '0 0');
// remove the following line in productive environment
$('.container').text($('.container').css('background-position'));
});

/* The following function will set the background-position
* to the given values. It has to be called in another function
* (see mouseover in your code).
*/
window.Bg = function(left,top) {
$('.container').css('background-position', left+ 'px ' + top + "px");
// remove the following line in productive environment
$('.container').text($('.container').css('background-position'));
}
});

关于jquery - 使用 jquery 添加 css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9901863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com