简体   繁体   中英

How to load a local image into a button

I'm writing in a js file and here is how my buttons look like

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

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 . Could you help me please?

Thanks

I would use a psuedo element, documented here: 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

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/

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...

JSBin Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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