简体   繁体   中英

Switching/Linking to another external stylesheet in a .js file using Ruby on Rails

Im learning JQuery from a Sitepoint Book but Im trying to apply all the lessons to a Rails App. In one lesson, we are taught how to switch to a different stylesheet if the browser window is resized beyond a certain point. Here's the javascript code:

if ($('body').width() > 900) {
  $('<link rel="stylesheet" href="wide.css" type="text/css" />')
    .appendTo('head');
} else {
  $('link[href=wide.css]').remove();
}

Rails doesn't seem to want to link to the new stylesheet using 'link rel'. I've tried using the Rails helper: <%= stylesheet_link_tag 'base', :media => 'screen' %> but that doesn't work in a .js file.

How do I link to an external stylesheet in a .js file using Ruby? Can I use Ruby on Rails code in a .js file?

Thanks.

I suspect that your problem is with the URL. There's probably something (directory name) that needs to go before the "wide.css" filename.

Try coding the link directly into the page. Look at the generated HTML and see what the Rails tag uses for the "href" value, and then use that yourself in the Javascript version.

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