如何使用 JQuery 修改具有已知 ID 的元素的 STYLE 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1457740/
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
How to modify STYLE attribute of element with known ID using JQuery
提问by MoreThanChaos
I got 3 buttons-links triggering some javascript code, with indication if certain button is selected, selected button got style attribute set to
我有 3 个按钮链接触发了一些 javascript 代码,指示是否选择了某个按钮,所选按钮的样式属性设置为
"btn brown selected"
“选择了 btn 棕色”
while other buttons got this attribute set to
而其他按钮将此属性设置为
"btn brown"
“btn 棕色”
only one button can be selected at one time, each of buttons got different unique id, my question is how using jquery access certain button to modify it's style attr. What i need its only how to access by id single button and modify its style attribute to get immediate update on the screen
一次只能选择一个按钮,每个按钮都有不同的唯一 id,我的问题是如何使用 jquery 访问某个按钮来修改它的样式属性。我只需要它如何通过 id 单个按钮访问并修改其样式属性以在屏幕上立即更新
thanks in advance MTH
提前致谢
回答by MaxiWheat
Use the CSS function from jQuery to set styles to your items :
使用 jQuery 中的 CSS 函数为您的项目设置样式:
$('#buttonId').css({ "background-color": 'brown'});
回答by cletus
Not sure I completely understand the question but:
不确定我是否完全理解这个问题,但是:
$(":button.brown").click(function() {
$(":button.brown.selected").removeClass("selected");
$(this).addClass("selected");
});
seems to be along the lines of what you want.
似乎与您想要的一致。
I would certainly recommend using classes instead of directly setting CSS, which is problematic for several reasons (eg removing styles is non-trivial, removing classes is easy) but if you do want to go that way:
我当然会推荐使用类而不是直接设置 CSS,这有几个原因(例如,删除样式很重要,删除类很容易),但如果您确实想这样做:
$("...").css("background", "brown");
But when you want to reverse that change, what do you set it to?
但是当你想扭转这种变化时,你把它设置成什么?
回答by user1798002
$("span").mouseover(function () {
$(this).css({"background-color":"green","font-size":"20px","color":"red"});
});
<div>
Sachin Tendulkar has been the most complete batsman of his time, the most prolific runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting is based on the purest principles: perfect balance, economy of movement, precision in stroke-making.
</div>