当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - jQuery class selector doesn't work and id selector works only with "body"

问题描述:

I'm trying to apply CSS values with jquery but class selector or id selector does not not work for some reason.

Here is my fiddle:

As you can see nothing happens if I use id="kitten".

HTML

 <div id="kitten"></div>

Script

 $(function(){

var x = 0;

setInterval(function(){

x-=1;

$("kitten").css("background-position", x + "px 0");

}, 10);

});

CSS

 html, body { height: 100%; width: 100%;}

#kitten {

background-image: url("http://sereedmedia.com/srmwp/wp-content/upload/kitten.jpg");

background-repeat: repeat-x;

}

It does not work. However if I use "body" instead of id - all starts to work.

Fiddle with "body"

Why I cannot use jQuery id selector or class selector?

网友答案:

First you need do:

$("#kitten").css("background-position", x + "px 0");

Becouse you are not getting the Id selector.

And define a width and height to your div, to show your image like:

#kitten {
    background-image: url("http://sereedmedia.com/srmwp/wp-content/uploads/kitten.jpg");
    background-repeat: repeat-x;
    width: 390px; <----- LIKE this
    height: 200px; <----- LIKE this
}

DEMO

网友答案:

To reference an id you need to use hash before the id itself, just like you do in css. The correct code would be:

$("#kitten").css("background-position", x + "px 0");
网友答案:
 $("kitten").css("background-position", x + "px 0");

this line is wrong..

this one will do the trick

 $("#kitten").css("background-position", x + "px 0");

you need to put the right string literals for ID selectors check it right here.

网友答案:

Id selectors are prefixed with #:

$("#kitten").css("background-position", x + "px 0");

A class selector would be prefixed with a ., for instance if kitten were a class:

$(".kitten").css("background-position", x + "px 0");

When you use the body selector you are using a tag selector which has no prefix.

$("input"); //selects all input tags

For most basic selectors, just follow CSS selector syntax.

网友答案:

Your selector is missing the # which is used for selecting tags by id:

$("#kitten")
分享给朋友:
您可能感兴趣的文章:
随机阅读: