滚动到该部分时将执行功能

时间:2016-03-07 06:17:06

标签: javascript jquery

我有这些代码用于在textarea占位符中创建一个打字脚本。它工作正常。但我需要执行typeIt函数当我滚动到表单div。

var txt =“滚动到该部分时将执行函数”;         var modified_txt =“”;

NSEvent

2 个答案:

答案 0 :(得分:0)

您需要捕获并为滚动事件指定事件处理程序。

为了演示目的,我采用了一些带有一些虚拟数据的div

HTML内容

<div id="scrollDiv" style="width:50px;height:50px;overflow:scroll;" >We've Worked For a lot of people and of course we've made them so happy! You can read some handpicked Word about us here We've Worked For a lot of people and of course we've made them so happy! You can read some handpicked Word about us here

We've Worked For a lot of people and of course we've made them so happy! You can read some handpicked Word about us here We've Worked For a lot of people and of course we've made them so happy! You can read some handpicked Word about us here</div>

Jquery

  $('#scrollDiv').scroll(function(){
alert('scrolling');
});

答案 1 :(得分:0)

你可以这样使用它(例如你的代码库):

<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
<div id="2">2</div>
<div>2</div>
<div>2</div>
<div>2</div>

<script>
    var oTop = $('#2').offset().top - window.innerHeight;
    $(window).scroll(function () {

        var pTop = $('body').scrollTop();
        console.log(pTop + ' - ' + oTop);   //just for your debugging
        if (pTop > oTop) {
            alert();
        }
    });

    function humanize() {
        return Math.round(Math.random() * (200 - 30)) + 30;
    }

    //Delete final character in modified string
    function deleteCharacter(text) {
        //return everything but the last character
        text = text.substring(0, text.length - 1);
        return text;
    }

    //Insert character_added at end of text
    function addCharacter(text, character_added) {
        text = text + character_added;
        return text;
    }

    //typos[char].error is just a self reference, it is not used
    var typos = {
    }

    var timeOut;
    var txtLen = txt.length;
    var char = 0;
    $('textarea').attr('placeholder', '|');
    function typeIt() {
        modified_txt += txt.charAt(char);
        $('textarea').attr('placeholder', modified_txt + '|');

        if (char === txtLen) {
            $('textarea').attr('placeholder', $('textarea').attr('placeholder').slice(0, -1)); // remove the '|'
            return; //Stop the loop once text is completely written.
        }

        var test = typos[char];
        if (test !== undefined) {
            setTimeout(function () {
                var chunk_one = test.correction(modified_txt);
                modified_txt = chunk_one;
                char++;
                typeIt();
            }, humanize());
        }
            //If no typos are found then move to the next character
        else {
            setTimeout(function () {
                char++;
                typeIt();
            }, humanize());
        }
    }

    $(function () {
        typeIt();

    });//end jquery
</script>