如何在 javascript 中更改按钮大小

问题描述 投票:0回答:5

我正在使用 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 文件,所以如果您不介意,请告诉我该怎么做。

谢谢。

javascript css button size
5个回答
4
投票

在将按钮元素附加到正文之前使用

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
这样的属性,您不能将
-
用作 一个对象键,所以你要做的方法是
camelCasing
就像这样
fontSize


1
投票

您可以使用

className
cssText
来执行此操作。 如果您使用了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;
}


0
投票

下面的代码怎么样?

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

0
投票

将其放入 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>

0
投票
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(
© www.soinside.com 2019 - 2024. All rights reserved.