0

我是 javascript 和 jquery 的新手,当我将鼠标悬停在 li 项目上时,我正在尝试更改视频的不透明度。我知道'onmouseover' 有效,因为我已经使用我用来滚动到页面顶部的相同jquery 进行了测试。

问题似乎是检查和更新视频 div 样式的语法不起作用。我从 codeacademy 的一堂课中改编了代码,但不明白它为什么起作用:

window.onload = function () {

    // Get the array of the li elements    
    var vidlink = document.getElementsByClassName('video');

    // Get the iframe
    var framecss = document.getElementsByClassName('videoplayer1');

    // Loop through LI ELEMENTS   
    for (var i = 0; i < vidlink.length; i++) {
        // mouseover function:
        vidlink[i].onmouseover = function () {
            //this doesn't work:
            if (framecss.style.opacity === "0.1") {
                framecss.style.opacity = "0.5";
            }
        };
        //onclick function to scroll to the top when clicked:
        vidlink[i].onclick = function () {
            $("html, body").animate({
                scrollTop: 0
            }, 600);
        };
    }
};

这是一个 jsfiddle,您可以看到 html 和 css:

http://jsfiddle.net/m00sh00/CsyJY/11/

这似乎是一个如此简单的问题,所以如果我遗漏了一些明显的东西,我很抱歉。

任何帮助深表感谢

4

1 回答 1

1

Try this:

    vidlink[i].onmouseover = function () {
        if (framecss[0].style.opacity === "0.1") {
            framecss[0].style.opacity = "0.5";
        }
    };

Or alternatively:

var framecss = document.getElementsByClassName('videoplayer1')[0];

Or, better, give the iframe an id and use document.getElementById().

The getElementsByClassName() function returns a list, not a single element. The list doesn't have a style property. In your case you know the list should have one item in it, which you access via the [0] index.

Or, given that you are using jQuery, you could rewrite it something like this:

$(document).ready(function(){
    // Get the iframe
    var $framecss = $('.videoplayer1');

    $('.video').on({
        mouseover: function () {
            if ($framecss.css('opacity') < 0.15) {
                $framecss.css('opacity', 0.5);
            }
        },
        click: function () {
            $("html, body").animate({
                scrollTop: 0
            }, 600);
        }
    });
});

Note that I'm testing if the opacity is less than 0.15 because when I tried it out in your fiddle it was returned as 0.10000000149011612 rather than 0.1.

Also, note that the code in your fiddle didn't run, because by default jsfiddle puts your JS in an onload handler (this can be changed from the drop-down on the left) and you then wrapped your code in window.onload = as well. And you hadn't selected jQuery from the other drop-down so .animate() wouldn't work.

Here's an updated fiddle: http://jsfiddle.net/CsyJY/23/

于 2013-08-03T13:58:12.320 回答