简体   繁体   中英

Display image with css when button is clicked

I'm attempting to display an image along with some css when 'Blue' is clicked in this fiddle : http://jsfiddle.net/adrianjsfiddlenetuser/C6Ssa/25/

But the image is not being displayed and the css is not being applied ?

The width and height properties in myImage class were too small for the image to show.

I tried this and it worked:

.myImage{
    ...
    width:60px;
    height:70px;
    ...
}​

Check it out here: http://jsfiddle.net/S6Ntn/

The image you are trying to display is 256x256px but the div you are using is 6x7px so only a tiny (and transparent) area of it is showing. If you want the whole X to show then you'll either need to resize the image to the correct dimensions, use an img tag or use background-size: 100% (CSS3 so browser support is limited)

Update

Updated jsFiddle
Here is a working sample of using the img tag instead of a background. The width and height are still getting set in css, but the src is now set within the javascript.

JavaScript

$("#red").click(red);
$("#blue").click(blue);

function red()
{
    $("#myDiv").removeClass('blue')
        .addClass('red')
        .text('test')
        .remove('img');
}

function blue()
{
      $("#myDiv").removeClass('red')
          .addClass('blue')
          .text('test')
          .append('<img src="http://oneseasonnation.com/www/wp-content/uploads/2008/11/2009/01/ip_icon_02_cancel.png" />');
}

CSS

.red
{
    background-color : red   
}
.blue
{
    background-color : blue   
}
.blue img
{
    width:25px;
    height:25px;
}

Original

You're setting it as a background with a fixed width and height. Background image scaling isn't widely supported, so it may be easier to add an image to the div with a specified height and width. You'll need to explicitly add it as an img tag, using the append jQuery method.

Your image is getting set, but it's not visible as it's too large, to demonstrate this I've updated your jsFiddle with increased widths and heights for the #myImage div.

If you carefully see, the image is being displayed and css is also being applied. Whenever you click, there's a small gray-ish box in the far right (you need to scroll probably). That's where the image is loaded. AND, you had a typing error. Instead of addClass('myImage') you used removeClass('myImage') . Besides that, you didn't utilize the powerful feature of chaining. Check out the update code. It's better and it works.

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