简体   繁体   中英

Using jQuery to set CSS attribute

First ever post to Stackoverflow and coding newb. I have seen many a example in which people have successfully set CSS attributes using jQuery. 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. However, I cannot get it to work using 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)

CSS

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

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..

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.

You may need to wrap the buttonPointer definition in a document.ready call, depending on the order of your source code.

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

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

$(window).resize(updatePointer); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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