开发者

How to use css in jquery

开发者 https://www.devze.com 2023-03-19 06:19 出处:网络
css: .level0 ul {list-style-type: none; height: 80px; width: 600px; margin: auto;} .level0 li {float: left;}

css:

.level0 ul {list-style-type: none; height: 80px; width: 600px; margin: auto;}
    .level0 li {float: left;}
    .level1 ul {list-style-type: none; height: 80px; width: 600px; margin: auto;}
    .level1 li {float: left;}
    .level2 ul {list-style-type: none; height: 80px; width: 600px; margin: auto;}
    .level2 li {float: left;}

css in javascript:

    <script>
fun开发者_如何学编程ction getId(id){
           $('.level'+id +' ul').css('list-style-type: none', 'height: 80px', 'width: 600px', 'margin: auto');
            $('.level'+id +' li').css('float: left');
}
    </script>

When I use css normal is ok, but when using css in javascript is error, can you help me ?


Why didn't you read the .css() docs?!

$('selector').css({
    attr: 'value',
    anotherattr: 'anothervalue'
});

Note that attrs use the JavaScript syntax for CSS attributes, i.e. lowerCamelCase instead of lower-with-dashes. That means listStyleType instead of list-style-type for example.

Besides that, only use .css() if you cannot use regular CSS. In many cases it's more appropriate to create a CSS class and the .addClass() this class.


You can pass parameters to css method in two ways:

$('.level'+id +' ul').css("property","value");

or multiple properties using an javascript object:

$('.level'+id +' ul').css({"property1":"value1","property2","value2"});


Bad syntax. You need squiggly brackets on multiple css items. Also, quote each element, not the whole entry. See below:

<script>
function getId(id){
       $('.level'+id +' ul').css({
           'listStyleType': 'none', 
           'height': '80px', 
           'width': '600px', 
           'margin': 'auto'
       });
        $('.level'+id +' li').css('float: left');
}
</script>


I think your problem is that the Jquery code should be within $(document).ready(function()

$(document).ready(function() {
  $('.level'+id +' ul').css('list-style-type: none', 'height: 80px', 'width: 600px', 'margin: auto');
  $('.level'+id +' li').css('float: left');
});

otherwise the javascript is going to be called before the HTML exists and no css will be applied since there is not HTML to apply it to.


You need the syntax $(selector).css('property', 'value'); Check out the documentation:

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

And a working sample I put up:

http://jsfiddle.net/awGrk/17/

0

精彩评论

暂无评论...
验证码 换一张
取 消