簡體   English   中英

我的用戶腳本不起作用,我也不知道為什么(過度使用var關鍵字)

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

嗨,大家好,我剛剛發現了用戶腳本的缺點,所以我想創建一個。 從數量有限的在線教程中,我設法提出了這一點。

// ==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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM