CSS在bookmarklet中不适用

CSS not applying in bookmarklet

本文关键字:不适用 bookmarklet CSS      更新时间:2023-09-26

我正在创建一个简单的bookmarklet(以前从未这样做过),虽然脚本执行得很好(现在没有做太多),但是嵌入的CSS样式表不适用于HTML。

激活链接如下(域更改):

<a href="javascript:(function(){document.head.appendChild(document.createElement('script')).src='http://www.mydomain.co.uk/cloudlr/app/js/cloudlr.js?rand=' + Math.floor(Math.random()*99999);})();">Do this</a>

这个脚本叫做:

if (typeof jQuery == 'undefined') {
    appendjQuery();
} else {
    jsVersion = $().jquery;
    versionArray = jsVersion.split('.');
    if (versionArray[1] < 6) {
        appendjQuery();
    } else {
        runthis();
    }
}
function appendCSS() {
    var cloudlrCSS = document.createElement('link');
    cloudlrCSS.type = 'text/css';
    cloudlrCSS.href = 'http://www.mydomain.co.uk/cloudlr/app/css/screen.css';
    cloudlrCSS.media = 'all';
    document.head.appendChild(cloudlrCSS);
}
function appendjQuery() {
    var cloudlrJS = document.createElement('script');
    cloudlrJS.type = 'text/javascript';
    cloudlrJS.onload = runthis;
    cloudlrJS.onreadystatechange = function () {
        if (this.readyState == 'loaded' || this.readyState == 'complete') {
            runthis();
        }
    }
    cloudlrJS.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js';
    document.head.appendChild(cloudlrJS);
}
function runthis() {
    appendCSS();
    $(document).ready(function() {
        $("img").each(function() {
            var $this = $(this);
            var imageWidth = $(this).width();
                $(this).before(imageWidth);
        });
        var cloudlrOverlay = '<div id="cloudlr-content">This is some content.</div><div id="cloudlr-overlay"></div>';
        $("body").append(cloudlrOverlay);
    });

}

希望这些都很简单。

脚本执行得很好(jQuery),但没有应用CSS。如果我查看"生成的源代码",我可以看到CSS被很好地插入,并且指向该文件的链接正常工作。所以我不知道发生了什么。

我是新手,欢迎任何关于最佳实践的额外建议以及问题的解决方案。

很多谢谢,迈克尔。

$("img").each(function(i,n) {
    var $this = $(n);//don't know why this is here but hey
    var imageWidth = $(n).width();
        $(n).before(imageWidth);
});
这是一个常见的错误…我想这会对你有帮助