我的用户脚本没有'我不工作;我不知道为什么(过度使用var关键字)

My userscript doesn't work and I don't know why (overuse of var keyword)

本文关键字:为什么 关键字 var 我不知道 工作 脚本 用户 我的      更新时间:2023-09-26

嘿,伙计们,我刚刚发现了用户脚本的愚蠢之处,我想创建一个。从有限的在线教程中,我设法想出了这个。

// ==UserScript== 
// @name My add on
// @description A script that adds a green div to the bottom of the page 
// @include http://*
// @grant none
// ==/UserScript== 
function createDiv(){
var userBar=document.createElement('DIV');
var userBar.style.height='80px';
var userBar.style.width='100%';
var userBar.style.backgroundColor='green';
document.body.appendChild(userBar);
}
createDiv();

这只是一个测试脚本,它在页面底部添加了一个绿色div。不幸的是,它在实现时什么都不做。

这个问题是因为您总是在前面写var。您只能在声明期间执行此操作。

这是正确的:

function createDiv(){
    var userBar=document.createElement('DIV');
    userBar.style.height='80px';
    userBar.style.width='100%';
    userBar.style.backgroundColor='green';
    document.body.appendChild(userBar);
}
createDiv();

此外,由于您说过要将其添加到网站底部,您可以在将元素添加到正文之前添加:

userBar.style.position='absolute';
userBar.style.bottom='50px';

试试这个:

...
var body = document.getElementsByTagName("body")[0];
    body.appendChild(userBar);