用 javascript 写 css 属性 不能正常工作
Writing css property with javascript doesn't work properly
我正在尝试通过 js 编写一些 css 属性,并且它可以正常使用以下代码:
$('.my-class-name').css({
width: '100px'
});
但是如果我添加一个包含连字符的 属性,例如 "border-right",它不起作用,例如:
$('.my-class-name').css({
width: '100px',
border-left: '10px #000000 solid'
});
使用 'border-left'
或 borderLeft
。正如 jQuery 网站所述:
CSS properties that normally include a hyphen need to be camelCased in
JavaScript. For example, the CSS property font-size is expressed as
fontSize when used as a property name in JavaScript. However, this
does not apply when passing the name of a CSS property to the .css()
method as a string – in that case, either the camelCased or hyphenated
form will work.
$('.my-class-name').css({
width: '100px',
'border-left': '10px #000000 solid'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-class-name">div</div>
或
$('.my-class-name').css({
width: '100px',
borderLeft: '10px #000000 solid'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-class-name">div</div>
我正在尝试通过 js 编写一些 css 属性,并且它可以正常使用以下代码:
$('.my-class-name').css({
width: '100px'
});
但是如果我添加一个包含连字符的 属性,例如 "border-right",它不起作用,例如:
$('.my-class-name').css({
width: '100px',
border-left: '10px #000000 solid'
});
使用 'border-left'
或 borderLeft
。正如 jQuery 网站所述:
CSS properties that normally include a hyphen need to be camelCased in JavaScript. For example, the CSS property font-size is expressed as fontSize when used as a property name in JavaScript. However, this does not apply when passing the name of a CSS property to the .css() method as a string – in that case, either the camelCased or hyphenated form will work.
$('.my-class-name').css({
width: '100px',
'border-left': '10px #000000 solid'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-class-name">div</div>
或
$('.my-class-name').css({
width: '100px',
borderLeft: '10px #000000 solid'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-class-name">div</div>