简体   繁体   English

未定义的CSS属性(顶部/左侧)

[英]Undefined CSS attribute (top/left)

So I have this code: HTML: 所以我有这个代码:HTML:

<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="script.js"></script>
    <title>Joc</title>
</head>
<body onload="funcio()">
    <img src="juanca.jpg" class="rey">
    <img src="elefant.gif" id="elefant">
    <button id="boton"> press me!</button>
</body>
</html>

CSS: CSS:

body {
    background-image:url("hierba.jpg");
}
.rey {
    width: 100px;
    height: 100px;
    position: absolute;
    top: 0px;
    left: 0px;
    transition: top 5s linear, left 5s linear;
}
.reyMov{
    width: 100px;
    height: 100px;
    position:absolute;
    top:1px;
    left:1px;
}
#elefant{
    width: 100px;
    height: 100px;
    position: absolute;
    top: 500px;
    left: 700px;
}
#boton{
    position: absolute;
    top:50px;
    left: 45%;
}

JS: JS:

function funcio(){
        alert("reyMov orig top "+$(".reyMov").css("top"))
        var posicio = $("#elefant").position();
        $(".reyMov").css("top",posicio.top+"px;");
        var posicio2 = $(".reyMov").position();
        alert("reyMov new top "+posicio2.top);

}; };

As you can see, I have defined top and left attributes for the class reyMov on CSS, but when I try to acces it (with alert), the js console returns me "Uncaught TypeError: Cannot read property 'top' of undefined" 正如您所看到的,我已经在CSS上为类reyMov定义了top和left属性,但是当我尝试访问它时(带有alert),js控制台返回“未捕获的TypeError:无法读取未定义的属性'top'”

I also tried to change this attribute and get it again, but does not work. 我也尝试更改此属性并再次获取它,但不起作用。 Any tip for fixing this? 有没有解决这个问题? Thank you! 谢谢!

if you don't use an element with class reyMov in the page then $(".reyMov") won't return any element: thus you are chaining the css() method to an empty object and the alert statement will throw that error. 如果你不在页面中使用带有类reyMov的元素,那么$(".reyMov")将不会返回任何元素:因此你将css()方法链接到一个空对象,并且alert语句将抛出该错误。

I suppose you are mistyping rey/reyMov in the javascript code (or the classname in the markup should be reyMov instead of rey ) 我想你是在javascript代码中rey/reyMov地输入rey/reyMov (或者标记中的classname应该是reyMov而不是rey

In JQuery, $("") is a selector, it selects elements from the DOM. 在JQuery中,$(“”)是一个选择器,它从DOM中选择元素。 You've not used the .reyMov class anywhere in your HTML. 您没有在HTML中的任何位置使用.reyMov类。 You're using jQuery to edit your CSS, at least not in your implementation. 您正在使用jQuery编辑CSS,至少在您的实现中没有。

I think you'd want to bind to an element, and apply a class using addClass, or then use the css method to change the css already applied. 我想你想要绑定到一个元素,并使用addClass应用一个类,或者然后使用css方法来更改已经应用的css。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM