Javascript选择框 - 显示图像而不是文本

时间:2017-01-20 00:09:32

标签: javascript html css

我目前有2个选择框,第一个下拉选项然后填充第二个选择框。一旦选择了两个选项,就会出现一个GO按钮,根据您的选择将您带到一个链接。我希望能够将此GO按钮从文本更改为图像。它的造型如下:

     if (!goButton) {
    //If the element doesn't exist, make it.
    goButton = document.createElement('button1');
    goButton.innerHTML = "Go!";
    goButton.style.display = "inline-block";
    goButton.style.fontWeight = "500";
    goButton.style.fontcolor = "white";
    item.parentNode.appendChild(goButton); //add it to the parent of the item argument.
    goButton.setAttribute('onclick', 'goButtonGo()');
    goButton.setAttribute('id', 'go-button');
  } else {
    //If it does exist, make sure you can see it.
    goButton.style.display = 'inline-block';
  }
}

任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:1)

使用按钮,您只需设置background-image

var button = document.createElement('button1');
button.style.display = "inline-block";
button.style.backgroundImage = 'url(https://codepo8.github.io/canvas-images-and-pixels/img/horse.png)';
button.style.backgroundSize = 'cover';
button.style.width = '100px';
button.style.height = '100px';
document.getElementById('box').appendChild(button);
<div id="box"></div>

您还可以创建<input type="image">元素

var button = document.createElement('input');
button.type = 'image';
button.src = 'https://codepo8.github.io/canvas-images-and-pixels/img/horse.png';
document.getElementById('box').appendChild(button);
<div id="box"></div>

答案 1 :(得分:0)

我建议将样式保存在CSS中而不是由JS处理

.goButton {
    font-weight: 500;
    color: white;
    background-image: url("the/url/of/your/image.jpg");
}
.goButton .selected {
    display: inline-block;
}

然后你需要管理样式就是设置这段代码

if (goButton.className) goButton.className =  "selected";
else                    goButton.className += " selected";