简体   繁体   English

使用JavaScript添加样式表IE 8

[英]Adding a style sheet IE 8 with JavaScript

I'm making a zoom button to add and remove a CSS file and for some reason I can't seem to add it in IE 8 我正在使用一个缩放按钮来添加和删除CSS文件,由于某种原因,我似乎无法在IE 8中添加它

First I tried this 首先我尝试了

document.createStyleSheet('style/zoom.css');

given that the jquery solution 鉴于jQuery的解决方案

$("head").append($("<link my style sheet />"));

seems to only work in FF and IE9 via my testing 通过我的测试似乎只能在FF和IE9中工作

I checked around the overflow and found this solution 我检查了溢出并找到了解决方案

 $('#zoomlink').replaceWith($('<link>', {
        id: 'zoomlink',
        href: 'style/zoom.css',
        type: 'text/css',
        rel: 'stylesheet' 
 }));

But still no love to be found so then frustrated i found this 但是仍然找不到爱,所以沮丧的是我发现了这个

var $link = $('&lt;link&gt;');
    $('head').add($link);
    $link.attr({
      type: 'text/css',
      href: 'style/zoom.css',
      type: 'text/css',
      rel: 'stylesheet',
      media: 'screen'
});

which im not certain would ever work but then finally i decided it way time to simply post a question. 我不确定是否可以使用,但是最后我决定是时候发布一个问题了。

I'm still not certain on how to remove the style sheet later via javascript but I need to first determine how to add a new style sheet in IE 8. 我仍然不确定如何稍后通过javascript删除样式表,但是我首先需要确定如何在IE 8中添加新样式表。

Maybe this will help (Sorry, can't try it in IE8): 也许这会有所帮助(对不起,无法在IE8中尝试):

(function() {
    var s  = document.createElement('link');
    s.type = 'text/css';
    s.rel  = 'stylesheet';
    s.href = 'http://yourdomain.com/style.css';
    document.getElementsByTagName("head")[0].appendChild(s);
})();

To remove it I would assume a simple remove() would work 要删除它,我假设一个简单的remove()可以工作

$("#zoomlink").remove();

To add a new link using jQuery with this syntax: 要使用具有以下语法的jQuery添加新链接:

$("head").append(unescape("%3Clink id='zoomlink' rel='stylesheet' type='text/css' href='style/zoom.css'%3E%3C/link%3E"));

or using pure JavaScript 或使用纯JavaScript

var e = document.createElement('link');
e.id = 'zoomlink'
e.rel = 'stylesheet';  
e.type='text/css';
r.href='style/zoom.css'
document.getElementsByTagName("head")[0].appendChild(e);

There is many other way of writing the same but the idea is the same, remove the old reference element and add a new one. 有许多其他相同的书写方式,但是想法是相同的,删除旧的引用元素并添加一个新的引用元素。

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

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