静音不适用于动态创建的视频

muted does not work for dynamically created videos

我创建了一个使用 src

动态创建视频标签的插件

plugin.js

(function($)
{
    $.fn.Video = function(props)
    {
        $(this).html('');
        var src = $(this).data('src');      
        var source = $('<source />', {src: src, type: 'video/mp4'});
        var obj = {'controls': ''};
        if(props != undefined)
        {
            if('muted' in props)
            {
                console.log('\t muted on');
                var muted = props['muted']
                if(muted == true)
                {
                    obj['muted'] = '';
                }
            }
        }
        var video = $('<video />', obj);
        video.css({'width': '100%'});
        video.append(source);
        video.append('Your browser does not support the video tag');
        $(this).append(video);
        return this;
    };
}(jQuery));

例子

<div class="video" data-src="http://video.archives.org/video.mp4"></div>
$('.video').Video({muted: True});

视频是这样渲染的

<div class="video" data-src="http://video.archives.org/video.mp4">
    <video controls="controls" muted="" style="width: 100%;">
        <source src="http://video.archives.org/video.mp4" type="video/mp4">Your browser does not support the video tag
    </video>
</div>

问题是 muted 在动态创建视频时不起作用。我该如何解决这个问题?

好吧,你设置静音的方式 属性 它不会工作,因为 属性仅用于初始化属性。它们不反映当前状态。 尝试链接语句,然后在视频上设置 attribute/property。

(function($) {
  $.fn.Video = function(props) {
    $(this).html('');
    var src = $(this).data('src');
    var source = $('<source />', {
      src: src,
      type: 'video/mp4'
    });
    var obj = {
      'controls': ''
    };
    if (props != undefined) {
      if ('muted' in props) {
        console.log('\t muted on');
        var muted = props['muted']
        if (muted == true) {
          obj.muted = 'muted';
        }
      }
    }
    var video = $('<video />', {
      controls: true
    }).prop('muted', muted);
    video.css({
      'width': '100%'
    });
    video.append(source);
    video.append('Your browser does not support the video tag');
    $(this).append(video);
    return this;
  };
}(jQuery));

$('.video').Video({
  muted: true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="video" data-src="https://www.w3schools.com/tags/movie.mp4"></div>