Javascript - 单击 svg 形状时调用函数。

标签 javascript html svg

我正在尝试做某种屏幕键盘。当我点击一个正方形时,它会在文本区域上写下一个特定的字母。

我想每次按下一个新方 block (并写一个新字母)时调用一个 JavaScript 函数。

使用真正的计算机键盘我会使用“keyup”。但在这里它不起作用(“mouseup”也不起作用)。

小演示: http://jsfiddle.net/bcorreia/oq0sgk8g/

谢谢

HTML

<svg width="60px" height="60px">

<rect width="50" height="50" onclick="getElementById('text').value+='a'">
</svg>

<svg width="60px" height="60px">
    <rect width="50" height="50" onclick="getElementById('text').value+='b'">
</svg>

<textarea id="text"></textarea>

JS

$(function(){
    $("#text").keyup(function() { 
        console.log("test");
    });
});     

最佳答案

我会稍微改变一下你的实现方式。不要为每个矩形使用不同的内联单击事件处理程序,而是以编程方式将单个单击事件委托(delegate)给所有矩形。为了区分应附加哪个字符,您可以将数据属性添加到包含它们所代表的字符的矩形,并在单击处理程序中检索它们的值。为了处理物理键盘输入,您有一个专门用于此的单独的事件绑定(bind)。这是一个我将如何解决这个问题的工作示例,其中有一些注释用于澄清它正在做什么。

    function yourOtherFunction(input) {
         console.log('You typed a "' + input + '"');   
    }
    
    $(function() {
        // Handle on-screen keyboard clicks (only on rects with a data-character
        // attribute present)
        $('svg rect[data-character]').click(function() {
            // Retrieve the "data-character" attribute value
            var character = $(this).data('character');
            // Modify the value of the textarea by appending the character
            $('#text').val(function(i, old) { return old + character; });
            // Call your other function
            yourOtherFunction(character);
        });

        // Handle physical keyboard key presses:
        $('#text').keypress(function(e) {
            // Retrieve the character representation of the event's key code
            var character = String.fromCharCode(e.which);
            // Call your other function
            yourOtherFunction(character);
        });
    });    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <svg width="60px" height="60px">
        <rect width="50" height="50" data-character="a" />
    </svg>
    <svg width="60px" height="60px">
        <rect width="50" height="50" data-character="b" />
    </svg>
        
    <textarea id="text"></textarea>

关于Javascript - 单击 svg 形状时调用函数。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27713591/

相关文章:

javascript - PHP/html : instant search function: Can't search for foreign (e. g.Chinese)字符

javascript 无法打开 google recaptcha

html - Bootstrap 3 列内的相对 div 不受尊重

css - 如何将变换原点设置为元素上的特定点?

html - 将 textPath 方向从逆时针方向翻转为顺时针方向?

html - 使用 Express.js 提供纯文本 SVG(与 Cheerio.js 相关的解决方案)

javascript - 维护 Chrome 打包应用程序的登录状态

javascript - 如何在 emberjs View 中处理 twitter bootstrap 按钮加载和重置

Javascript RegExp 非捕获组

html - 填充多边形 SVG 形状的图像