简体   繁体   English

用javascript隐藏SVG元素

[英]Hide SVG elements with javascript

I'm trying to make a javascript vector animation with SVG. 我正在尝试使用SVG制作javascript矢量动画。 At the start, there is a play button. 首先,有一个播放按钮。 When this is pressed, it starts the music and should hide itself. 按下此按钮时,它将开始播放音乐,并应隐藏起来。

This is my HTML: 这是我的HTML:

<audio>
        <source src="song.mp3" type="audio/mp3" />
    </audio>

    <svg id="canvas" xmlns:html="http://www.w3.org/1999/xhtml">

        <!-- Definitions -->
        <defs>
            <linearGradient id="white-grey" x1="0%" y1="0%" x2="0%" y2="100%">
                <stop offset="0%" style="stop-color:#F5F5F5;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#D9D9D9;stop-opacity:1" />
            </linearGradient>

            <linearGradient id="grey-white" x1="0%" y1="100%" x2="0%" y2="0%">
                <stop offset="0%" style="stop-color:#F5F5F5;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#D9D9D9;stop-opacity:1" />
            </linearGradient>
        </defs>

        <g id="play-button" onclick="start()">
            <rect x="300" y="200" rx="20" ry="20" width="200" height="100"
                fill="url(#white-grey)" stroke="#5E5E5E" stroke-width="2">
            </rect>
            <text x="361" y="259" fill="#5E5E5E" font-size="30">
                PLAY
            </text>
        </g>
    </svg>

And this is my javascript: 这是我的javascript:

function start() {

    try {
        $('audio').currentTime=0;
    }
    catch(e) {} 
    $('audio').play();

    $('#play-button').css({"visibility":"hidden"});

}

I found the first part of the code, which plays the music. 我找到了播放音乐的代码的第一部分。 However, the play button is not being hidden. 但是,播放按钮并未隐藏。 What is going wrong?? 怎么了?

Use detach instead - it removes the element from the dom but keeps the reference. 请改用detach-从dom中删除元素,但保留引用。

var playButton = $('#play-button');

function start() {

    try {
        $('audio').currentTime=0;
    }
    catch(e) {} 
    $('audio').play();

    playButton.detach();
}

//re-add playbutton
$('#canvas').append(playButton);

Set opacity in css for hide svg elements 在CSS中设置隐藏SVG元素的不透明度

 $('#play-button').css({"opacity": 0 });

Link 链接

Try to work with the SVG document itself: 尝试使用SVG文档本身:

var obj = $('#canvas').get(0);

obj.onload = function() {
  var doc = obj.contentDocument;

  doc.find('#play-button').click(function() {
    $(this).fadeTo(400, 0);
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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