簡體   English   中英

如何更改 javascript 中的按鈕大小

[英]How do I change a button size in javascript

我正在使用 javascript 在 chrome 擴展程序中創建按鈕,但我找不到更改按鈕大小的方法,這是代碼。

 var buttonShort = document.createElement("button"); buttonShort.innerHTML = "Generate Short Password"; var body = document.getElementsByTagName("body")[0]; body.appendChild(buttonShort); buttonShort.addEventListener ("click", function() { var newWindow = window.open(); newWindow.document.write("The generated Password is: '" + short() + "'"); newWindow.focus() });

我需要更改按鈕的大小(主要是寬度),所以如果您有任何建議,請說。 此外,如果您要說使用 CSS,我不知道如何將 CSS 文件添加到 javascript 文件,所以如果您不介意,請告訴我如何操作。

謝謝。

您可以使用classNamecssText來這樣做。 如果使用className,則需要在CSS中定義類。

 // By setting css class name var buttonShort = document.createElement("button"); buttonShort.innerHTML = "Generate Short Password"; // set class name buttonShort.className = "button"; var body = document.getElementsByTagName("body")[0]; body.appendChild(buttonShort); // Or using JS var buttonShort = document.createElement("button"); buttonShort.innerHTML = "Generate Short Password 2"; // set CSS name using js buttonShort.style.cssText = "border: 1px solid black; background-color:blue;height: 20px;color:white"; var body = document.getElementsByTagName("body")[0]; body.appendChild(buttonShort); 
 .button { border: 1px solid black ; background-color: orange; height: 20px; } 

在將button元素附加到正文之前,請使用style.width屬性,如下所示:

 var buttonShort = document.createElement("button"); buttonShort.innerHTML = "Generate Short Password"; var body = document.getElementsByTagName("body")[0]; buttonShort.style.width = '200px'; // setting the width to 200px buttonShort.style.height = '200px'; // setting the height to 200px buttonShort.style.background = 'teal'; // setting the background color to teal buttonShort.style.color = 'white'; // setting the color to white buttonShort.style.fontSize = '20px'; // setting the font size to 20px body.appendChild(buttonShort); buttonShort.addEventListener("click", function() { var newWindow = window.open(); newWindow.document.write("The generated Password is: '" + short() + "'"); newWindow.focus(); }); 

所有其他CSS屬性都可以通過style對象(寬度,高度,顏色等)訪問。

注意:當心諸如font-size類的屬性,您不能將-用作對象鍵,因此,您可以通過camelCasingfontSize這樣的方式來實現。

下面的代碼怎么樣?

var cssString = "{padding: 15px 20px; color: #F00;}";
buttonShort.style.cssText = cssString;

將其放入 head 標簽中:

<style>
p.ex3 {
      font-size: 15px;
    }
</style>

並將其放入正文中:

<div><p id="demo" class="ex0">Led Off</p></div>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Led 
On"'><p class="ex3">Led On</p></button>

暫無
暫無

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

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