javascript - 当 SVG 用作背景图像时,如何在单击时更改它的填充颜色?

标签 javascript jquery css svg

http://codepen.io/leongaban/pen/EChLK

这里的问题非常独特,当我的 SVG 用作 background image 时,不确定如何定位和更改它的填充颜色.在我的例子中,单击时将类 myGreen 交换为 myGray。

html

<div id="icon_phone">Phone</div>

CSS

#icon_phone {
    padding-left: 15px;
    height: 30px;
    font-family: Arial;
    background: url('http://leongaban.com/_codepen/svg/ico_my_phone.svg') no-repeat;
    background-size:10px 20px;
    cursor: pointer;
}

当前的 jQuery

$("#icon_phone").unbind('click').bind('click', function () {
    //$(this).css('background', 'none');
});

Illustrator 创建的 SVG 代码

<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 17.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 width="15px" height="28px" viewBox="0 0 15 28" enable-background="new 0 0 15 28" xml:space="preserve">

 <style type="text/css" >
  <![CDATA[

    path.myGreen {
       fill: #39B54A;
    }
    path.myGray {
        fill: #e2e2e2;
    }

  ]]>
</style>

<path class="myGreen" d="M12.861,0H2.144C0.965,0,0,1.03,0,2.287v22.556c0,1.259,0.965,2.287,2.144,2.287h10.717
c1.179,0,2.144-1.029,2.144-2.287V2.287C15.005,1.03,14.04,0,12.861,0z M5.721,2.137h3.572c0.236,0,0.305,0.537,0.305,0.79
c0,0.253-0.069,0.639-0.305,0.639H5.721c-0.236,0-0.206-0.386-0.206-0.639C5.515,2.675,5.485,2.137,5.721,2.137z M7.52,26.16
c-0.711,0-1.287-0.614-1.287-1.373c0-0.758,0.576-1.373,1.287-1.373c0.711,0,1.287,0.615,1.287,1.373
C8.808,25.546,8.231,26.16,7.52,26.16z M13.578,22.139H1.434V4.995h12.144V22.139z"/>

我在这里找到了如何将类添加到 svg 文件中: http://tutorials.jenkov.com/svg/svg-and-css.html

最佳答案

创建一个灰色背景图像文件并单击更改背景 URL 以指向备用图像。

Images cannot be manipulated by the host document. Think of SVG when used as an image as being like a scalable bitmap.

关于javascript - 当 SVG 用作背景图像时,如何在单击时更改它的填充颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19663259/

相关文章:

jQuery On Click 不起作用

css - Laravel & Vue 警告问题

asp.net - CSS 打印 - 分页前导致表头不重复(Internet Explorer 8)

JavaScript 关闭问题 : why is the second call to outerFn creating a new instance of outerVar?

javascript - React JS : how to properly remove an item from this. state.data 其中数据是一个对象数组

javascript - 如何使用 jasmine 模拟 jquery getJSON 回调

jquery - 如何在加载页面主体背景图像之前显示加载图像?

javascript - 使 D3 响应 : viewBox vs resize()?

javascript - 为什么 jquery 调整大小不起作用?

javascript - 切换 Div 对单选按钮选择问题的可见性