我喜欢用 JavaScript/Bookmarklets 拉动我的 Chrome/Chromium 体验, 但现在我面临以下问题:
代码
javascript:/*img2float*/ var str=prompt("src of img to float",document.querySelector("img").getAttribute('src'));str.length>0?content=str:content="Alap/Alap00.gif",document.querySelector("img[src*='"+content+"']").style.cssText="position:fixed;left:0;top:0;max-height:200px;box-shadow: 1px 1px 46px -21px;opacity:0.9";
解释
-
var src=prompt("src of <img> to float",document.querySelector("img").getAttribute('src'));
src 第一个 的 attribute
-
scr.length>0?
如果 NOT NULL -
var ThisDOM=src:
ThisDOM = 提示值, else -
ThisDOM="Alap/Alap00.gif",
默认,最常用的设置 -
document.querySelector("img[src*='"+ThisDOM+"']").
选择所需的 -
style.cssText=
添加所需的css 样式 -
"position:fixed;left:0;top:0;max-height:200px;box-shadow: 1px 1px 46px -21px;opacity:0.9";
css 样式设置
问题
- [✔] 从 DevTools>Console 运行代码,将 css 样式设置正确应用到图像,
- [ø] 但从 Bookmarklet 运行只是打印出 css 样式 settings(在 7 处解释.)
最佳答案
在美化上述问题的过程中,我尝试将代码包装在函数中,如下所述:javascript - function as google chrome bookmark终于成功了!
包装器
javascript:(function(){ })();
最终代码
javascript:/*img2float*/ (function(){var scr=prompt("src of img to float",document.querySelector("img").getAttribute('src'));scr.length>0?ThisDOM=scr:ThisDOM="Alap/Alap00.gif",document.querySelector("img[src*='"+ThisDOM+"']").style.cssText="position:fixed;left:0;top:0;max-height:200px;box-shadow: 1px 1px 46px -21px;opacity:0.9";})();
但我还是很好奇为什么没有函数包装器就不能工作?
关于javascript - 从控制台运行的脚本但从 Bookmarklet 打印变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58044137/