在javascript中将图像添加到按钮
我在javascript中创建了一个按钮,我想使用图像作为按钮而不是文本,但我还没有找到一种方法来做到这一点。 到目前为止,我引用的来源因某些原因不适合我。 到目前为止我所拥有的内容如下
使用Javascript
var sb=doc.createElement('input'); sb.type='button'; //sb.value='Find'; sb.src = "url(/Resources/Icons/appbar.next.rest.png)"; sb.style.height='100%'; //sb.style.width='20%';
我的图像在我的项目目录/Resources/Icons/appbar.next.rest.png
中的位置。 有人能指出我正确的方向,如何正确使用图像的按钮? 我是javascript的新手,所以任何链接,代码或方向都将非常感谢!
要将图像添加到按钮,您可以更改按钮到图像的输入类型:
var body = document.getElementsByTagName("body")[0]; var s = document.createElement("input"); s.src = "http://www.gravatar.com/avatar/a4d1ef03af32c9db6ee014c3eb11bdf6?s=32&d=identicon&r=PG"; s.type = "image"; body.appendChild(s);
你可以修改它。
Use input type="image", or use a button element with an child.
例如:
or
如果您打算使用按钮(在服务器上或在javascript中)执行任何操作,基于此页面建议对input type="image"
,似乎使用type="image"
可能会出现问题。
基本上,您应该使用CSS的background-image
属性,而不是使用按钮的pure-html属性来显示输入。
js匹配你的:
var sb=doc.createElement('input'); sb.type='button'; sb.class='myImageButton';
和这个CSS:
input.myImageButton { border: none; cursor: pointer; display: inline-block; text-indent: -3000px; background: url(/Resources/Icons/appbar.next.rest.png) no-repeat 50% 50%; /* width: 20%; */ height: 100%; }
应该管用。
值得指出的是,如果你没有对这个按钮的价值做任何事情 ,那么这个答案真的不值得你花时间。 但你最好确定一下。