1

如何编写javascript以单行样式设置元素?例如,

document.getElementById('add_new').style.top=-15;
document.getElementById('add_new').style.position='absolute';

是否可以使用 javascript 本身使其成为数组或单行来设置元素的样式?

如何为编写对对象的重复访问提供简写?

4

5 回答 5

4

我不推荐它,但你可以做这样的事情来把它放在“1”行:

with( document.getElementById('add_new').style ) { top=-15; position='absolute'; }

或其他方式:

element.style.cssText="background: black ; color: blue ; border: 1px solid green" 

感谢JavaScript 的“with”语句有合法用途吗?

于 2012-09-13T04:51:17.263 回答
3

你不能用 vanilla JavaScript 做到这一点。

如果你使用 jQuery,你可以使用一个对象:

$('#add_new').css({top: '-15px', position: 'absolute'});
于 2012-09-13T04:49:16.497 回答
1

本机 js 没有这样的东西,但如果你使用 jQuery,你可以使用以下代码

$('add_new').css({backgroundColor: '#ffe', borderLeft: '5px solid #ccc'})
于 2012-09-13T04:51:20.113 回答
0

这是最简单的方法:

Javascript

document.getElementById("add_new").classList.add('addstyle');

CSS

<style>
.addstyle
{
    top: -15;
    position: absolute;
}
</style>

或与 JQuery 为:

$('.add_new').css({top: '-15px', position: 'absolute'});
于 2012-09-13T04:50:43.860 回答
0

If you are willing to use jquery you can do it, but that's not completely within scope of the question. You will also have to notate it in the "jQuery" way. Here's a link for reference.

http://api.jquery.com/css/

It might look like:

$("#add_new").css({
    "top": "-15px",
    "position": "absolute"
});

Again, this is not in pure JavaScript as your question indicates. You will need an additional library to make it work.

于 2012-09-13T04:52:11.440 回答