简体   繁体   English

如何将本地图像加载到按钮中

[英]How to load a local image into a button

I'm writing in a js file and here is how my buttons look like 我正在写一个js文件,这是我的按钮外观

var myButton = $('<button type="button" style="display:inline">Translate Right</button>');
    myButton.css({"margin-top":"5px", "float":"left"});

Now I would like to replace the "Translate right" text with an icon. 现在,我想用一个图标替换“向右翻译”文本。 I tried : 我试过了 :

   var myButton = $('<button type="button" style="display:inline">Translate Right</button>');
       myButton.css({"margin-top":"5px", "float":"left"});
       $('body').append(myButton); 
      myButton.html('<img src="path\to\image">'); // backslash because I'm using windows

But it is not working. 但这是行不通的。 I have an empty button. 我有一个空按钮。 And I have this error: Not allowed to load local resource. 我有这个错误:不允许加载本地资源。 I changed url with src (I'm not sure if I'm allowed to do like this), I don't have the error anymorre but the button is still empty 我用src更改了网址(我不确定是否可以这样做),我没有任何错误,但按钮仍然为空

ps : In my code, I append myButton to the body in another way because, the file I'm writing in, is not my index file but the problem is not here (I have already tried with a different src http://static.jsbin.com/images/favicon.png ) and it worked . ps:在我的代码中,我以另一种方式将myButton附加到主体上,因为我正在写入的文件不是我的索引文件,但问题不在这里(我已经尝试过使用其他src http:// static .jsbin.com / images / favicon.png )并成功。 Could you help me please? 请问你能帮帮我吗?

Thanks 谢谢

I would use a psuedo element, documented here: http://css-tricks.com/pseudo-element-roundup/ 我会使用psuedo元素,在此处记录: http : //css-tricks.com/pseudo-element-roundup/

Also, I'd recommend not putting your css in your javascript but instead just change the class name via javascript, as described here: http://smacss.com/book/state 另外,我建议不要将CSS放入javascript中,而是通过javascript更改类名,如此处所述: http : //smacss.com/book/state

ie: 即:


.myButton:after{
  content: '';
  display: inline-block;
  width: 20px;
  height: 20px;
  background: (myIcon.png);
}

Edit: 编辑:

I think something has gone wrong with your code between trying various things. 我认为您尝试各种方法之间的代码出了点问题。 This JSFiddle works for me: http://jsfiddle.net/4C6e3/ 这个JSFiddle为我工作: http : //jsfiddle.net/4C6e3/

You could try something like: 您可以尝试类似:

var myButton = $('<button type="button" style="display:inline">Translate Right</button>');
myButton.css({"margin-top":"5px", "float":"left"});

And then: 接着:

myButton.html('<img src="path/to/icon" />');

But you should use <button> with this method... 但是您应该将<button>与这种方法结合使用...

JSBin Demo JSBin演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM