【问题标题】:How can I add event listener to this svg hardcoded in JS?如何将事件侦听器添加到这个用 JS 硬编码的 svg?
【发布时间】:2021-03-29 10:18:19
【问题描述】:

我在 JavaScript 的字符串中硬编码了这个 SVG 图标,但我无法为其添加侦听器。

let zoom_in_icon = '<div>';
zoom_in_icon = zoom_in_icon +'<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/>';
zoom_in_icon = zoom_in_icon + '<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm.5-7H9v2H7v1h2v2h1v-2h2V9h-2z" fill="white"/>';
zoom_in_icon = zoom_in_icon + '</svg>';
zoom_in_icon = zoom_in_icon + '</div>';

当我这样尝试时它失败了:

未捕获的类型错误:zoom_in_icon.addEventListener 不是函数

zoom_in_icon.addEventListener('mouseover', function (evt) {
    zoom_in_icon.style.cursor = 'pointer';
});
zoom_in_icon.addEventListener('mouseout', function (evt) {
    zoom_in_icon.style.cursor = 'auto';
});

是否可以这样做,或者我必须使用 DOM 使用纯 Javascript 创建这个 SVG?

更新: 现在我正在尝试使用纯 Javascript 创建一个 Div,这样我就可以直接引用 DOM 而不是字符串,这可能是它失败的原因。

var newElement = document.createElement('div');
let zoom_in_icon = '<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/>';
zoom_in_icon = zoom_in_icon + '<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm.5-7H9v2H7v1h2v2h1v-2h2V9h-2z" fill="white"/>';
zoom_in_icon = zoom_in_icon + '</svg>';
newElement.innerHTML = zoom_in_icon;

newElement.addEventListener('mouseover', function (evt) {
    newElement.style.cursor = 'pointer';        
});
newElement.addEventListener('mouseout', function (evt) {
    newElement.style.cursor = 'auto';
});

这还是不行!现在它没有失败,但是,div 中没有添加任何侦听器。当我悬停时,它不会改变光标。

【问题讨论】:

  • 您的变量zoom_in_icon 是一个文本字符串,而不是对DOM 元素的引用。见javascript.info/searching-elements-dom
  • @Danny'365CSI'Engelman 请检查更新后的问题。
  • 你的第二个版本对我来说非常好——假设newElement实际上在某个时候被附加到文档中。
  • “当我悬停时它不会改变光标。” - 你为什么要这样做首先使用事件监听器? cursor 属性一开始只适用于处于悬停状态的元素,因此您可以通过 CSS 应用它并完成它:div { cursor: pointer; }
  • @CBroe 我刚做过,以前不知道!

标签: javascript html svg dom-events


【解决方案1】:

你是在你的身体或其他任何地方添加你的 div 吗?

document.body.appendChild(newElement);

您可以通过以下方式更改您的 div 声明: let zoom_in_icon = '&lt;div id="zoom_in_icon "&gt;';

#zoom_in_icon 上更容易自定义css。

【讨论】:

    【解决方案2】:

    我在我的扩展 chrome projet 上使用 sprite svg,所以我使用了一个类 Sprite:

    class Sprite {
        /**
         * 
         * @param {string} url URL of file sprite.svg
         */
        constructor(url) {
            this.url = url;
            this.create();
        }
        
        /**
         * Load a file sprite SVG and add his DOM in your body at hidden
         * to be able to use icones of your sprite
         */
        create() {
            $.get(chrome.runtime.getURL(this.url), (data) => {
                var div = document.createElement('div');
                div.style.display = 'none';
                div.innerHTML = new XMLSerializer().serializeToString(data.documentElement);
                document.body.insertBefore(div, document.body.childNodes[0]);
            });
        }
    
        /**
         * Create a SVG element
         * @param {string} id Id of your icon
         * @param {number} width Width display
         * @param {number} height Height display
         * @returns {SVGSVGElement} SVG Element 
         */
        createSVG(id, width, height) {
            let svgElem = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            let useElem = document.createElementNS('http://www.w3.org/2000/svg', 'use');
            svgElem.setAttribute('width', width.toString());
            svgElem.setAttribute('height', height.toString());
            useElem.setAttributeNS('http://www.w3.org/1999/xlink', 'href', id);
            svgElem.appendChild(useElem);
            return svgElem;
        }
    }
    
    

    要使用它,我正在这样做:

    let spriteButton = new Sprite('assets/images/sprites/buttons.svg');
    let bt_prev = spriteButtons.createSVG('#ss_previous', 25, 25);
    let bt_play = spriteButtons.createSVG('#ss_play', 25, 25);
    

    对于悬停 css,我使用这个:

    // Default style
    $('#zoom_in_icon').css(styleButton);
    
    // Hover in & out style
    $('#zoom_in_icon').hover(
      (e) => {
        $(e.currentTarget).css(styleButtonHover);
      },
      (e) => {
         $(e.currentTarget).css(styleButton);
       },
    );
    

    这里是你的精灵 svg:

    <?xml version="1.0" encoding="utf-8"?>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <symbol viewBox="0 0 24 24" id="your_icon_id">
            <path fill="currentColor" d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm.5-7H9v2H7v1h2v2h1v-2h2V9h-2z"/>
        </symbol>
    </svg>
    

    在你的 CSS 中,你可以使用以下命令将颜色更改为白色:

    #your_icon_id {
      color: white;
    }
    

    希望对你有帮助:)

    【讨论】:

    • 我真的不明白这个语法。我正在使用 Javascript。
    • 主要是javascript和一些jquery。
    猜你喜欢
    • 2012-09-09
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2011-05-29
    • 2014-06-19
    相关资源
    最近更新 更多