使用 CSS 属性更改元素的背景
我有一个带有背景的 div,我想在单击时更改背景的位置。
这是我的 jQuery 片段:
$('#sprite').click(function () {
$(this).css('backgroundPosition', '-40px');
});
虽然工作正常,但我想通过“第二次”单击返回到原始位置,重置所有内容。
嗯,这就是所谓的“回调”吧?
我尝试过这样做,但没有成功:
$('#sprite').click(function () {
$(this).css('backgroundPosition', '-40px');
},function () {
$(this).css('backgroundPosition', '40px');
});
I have a div with a background, and I'd like to change the background's position on click.
This is my jQuery snippet :
$('#sprite').click(function () {
$(this).css('backgroundPosition', '-40px');
});
While this is working ok, I'd like to return to the original position with a 'second' click, resetting all.
Mmm, is this what's called a 'callback' right?
I tried so with that but it didn't work :
$('#sprite').click(function () {
$(this).css('backgroundPosition', '-40px');
},function () {
$(this).css('backgroundPosition', '40px');
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该考虑为此使用“切换”功能...它将允许您在 2 个不同的 CSS 类之间切换...查看本教程 这里。
与直接设置 CSS 属性不同的另一种选择是为您的背景创建一个 CSS 类,然后简单地切换该类。
CSS
jQuery
You should consider using a "toggle" function for this... It'll allow you to go between 2 different CSS classes... Check out this tutorial here.
Another option rather than setting the CSS property directly would be to create a CSS class for your background and simply toggle that class.
CSS
jQuery
您误解了回调的概念。 编程中的回调是在执行代码后立即调用的函数。
在您的情况下,您会说以下内容:
单击时,将我的背景位置设置为-40px。 完成后,将其设置为 40px(立即撤消函数刚刚执行的操作)。
在这种情况下,您不需要使用回调函数。 您需要设置一个切换开关,以便当用户单击您的元素时,会运行一个函数...然后,当用户下次单击该元素时,会运行第二个函数。
You're mis-understanding the concept of a callback. A callback in programming is a function that gets called immediately after the executing code.
In your case, you're saying the following:
On click, set my background position to -40px. Once you're done with that, set it to 40px (immediately undoing what your function just did).
In this case, you don't need to use a callback function. You need to set up a toggle so that when the user clicks on your element, one function is run...then the next time they click on that element, the second function is run.
用课堂来做。 这要容易得多。
Do it with classes. It's much much easier.