如何在Javascript中更改两个或多个Div样式

How to change two or more Div Styles in Javascript

本文关键字:两个 样式 Div Javascript      更新时间:2023-09-26

有没有办法用一行javascript更改两个或多个div样式?

document.getElementById("searchScroll").style.position="fixed";
document.getElementById("searchScroll").style.margin="-50px";

可以将代码合并到一行中吗?

您可以使用一行JavaScript更新它,但我建议将其保留为多行-使用多行更容易阅读和理解,而且不必担心替换其他样式值。

您可以升级一个级别并设置style,例如:

document.getElementById("searchScroll").style.cssText = "position:fixed;margin:-50px;";

这将替换当前样式。。要添加,您可以使用以下内容:

document.getElementById("searchScroll").style.cssText += "position:fixed;margin:-50px;";

示例:http://jsfiddle.net/aDMke/

您可以使用cssText属性。

document.getElementById("searchScroll").style.cssText = "position:fixed;margin:-50px"

但我将替换所有其他内联样式。

或者,使用jQuery:

$('#searchScroll').css({
    'position': 'fixed',
    'margin': '-50px'
});

您可以使用with(但Crockford不喜欢):

with(document.getElementById("searchScroll").style){position='fixed';margin='-50px';}

或者添加cssText属性(这可能是您想要的):

document.getElementById("searchScroll").style.cssText += 'position:fixed;margin;-50px';

演示:http://jsfiddle.net/V6gCC/