简体   繁体   中英

Running javascript to amend css

I have the following code which works fine on the jsfiddle environment. However I can't get it to run outside of it. Im relatively new to javascript so not sure. Do I need to declare the javascript as a function and have it run on page load? The CSS and JS files will ideally be external files if that makes any difference once they've been referenced in the head part of my html.

<html>  
   <head>
    <style>
    .container {
        width: 100%;
        height: 150px;
        background : #bbb;


    }
    .inner {
        float:left;
        height:100%;
        margin-left:20px;
    }
    </style>
    <script>    

    var containerW = $('.container').width();
    var innerCount = $('.container .inner').length;
    var containerM = parseInt($('.container .inner').css("margin-left"));

    $('.inner').css({
        width:  (containerW  / innerCount) - containerM  
    })   

    </script>

</head>
 <body>
    <div class='container'>
        <div class='inner' style='background : #FF0000;'></div>
        <div class='inner' style='background : #00FF00;'></div>
        <div class='inner' style='background : #FF0000;'></div>
        <div class='inner' style='background : #00FF00;'></div>
    </div>
  </body>    
</html>

DEMO

(My code is slightly different to the fiddle but the princple is the same I cant get it to work.

Thanks

You need to encapsulate your jQuery within document ready :

$( document ).ready(function() {
  var containerW = $('.container').width();
  var innerCount = $('.container .inner').length;
  var containerM = parseInt($('.container .inner').css("margin-left"));

  $('.inner').css({
      width:  (containerW  / innerCount) - containerM  
  })
});

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

You can also use the window onload function, see here for more info

The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (eg images) also has been loaded.

Source: this answer , coursesy of Guffa

you can always use 'show' feature of jsfiddle.com to see your code, example:

jsfiddle show

to see the code generated by jsfiddle just right click and see the source code, in your case it's as follows:

view-source: http://jsfiddle.net/yaLMk/4/show/

$(window).load(function(){
var containerW = $('.container').width();
var innerCount = $('.container .inner').length;

$('.inner').css({
    width: containerW / innerCount
})
});

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