简体   繁体   English

使用jQuery设置CSS属性

[英]Using jQuery to set CSS attribute

First ever post to Stackoverflow and coding newb. 第一次发布到Stackoverflow并编码newb。 I have seen many a example in which people have successfully set CSS attributes using jQuery. 我看过很多例子,其中人们已经使用jQuery成功设置了CSS属性。 However, after many frustrating hours, I have still yet to see what obvious thing is wrong. 但是,经过许多令人沮丧的时间,我仍然没有看到明显的问题是什么。 Here's my very simplified code. 这是我非常简化的代码。 I know that if I add this attribute manually to the CSS, it has the desired effect. 我知道,如果我将此属性手动添加到CSS,它将具有预期的效果。 However, I cannot get it to work using jQuery. 但是,我无法使其使用jQuery。 Any help or suggestions would be much appreciated. 任何帮助或建议,将不胜感激。 I feel as if this should be so obvious but I don't see it. 我觉得这似乎很明显,但我看不到。

I am using RoR (and I have included //=require jquery in app.js) 我正在使用RoR(并且我已经在app.js中添加了// = require jquery)

CSS CSS

    #magicaldiv{
                margin-left: -175px;
                margin-top: -20px;
                width:350px;
                height:40px;
                position:absolute;}

JS JS

     var buttonPointer = $('#magicaldiv');
     $(document).ready(updatePointer);
     $(window).resize(updatePointer); 
     function updatePointer(){
                              buttonPointer.css('left', 200);}

I have also tried several iterations of jQuery and JS including but not limited to.. 我还尝试了jQuery和JS的多次迭代,包括但不限于..

JS JS

     document.getElementById("magicaldiv").style.left = 200;

and

     var left = 200 + "px";
     buttonPointer.css('left', left);

and

     buttonPointer.css('left', '200px');

even though the documentation suggests that all numbers will be turned into a string and assumed to be px. 即使文档建议将所有数字都转换为字符串并假定为px。

You may need to wrap the buttonPointer definition in a document.ready call, depending on the order of your source code. 您可能需要将buttonPointer定义包装在document.ready调用中,具体取决于源代码的顺序。

var buttonPointer;
function updatePointer(){
  buttonPointer.css('left', 200);}

$(document).ready(function() {
  buttonPointer = $('#magicaldiv');
  updatePointer();
});

$(window).resize(updatePointer); 

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

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