jQuery滚动到下一个出现的文本

时间:2018-08-20 08:35:22

标签: jquery

我正在尝试在我的网页中创建一个搜索功能来搜索文本。如果找到该文本,则将其突出显示,否则将弹出一个弹出窗口,提示未找到任何内容。

我想在此搜索功能中添加其他2个功能。我创建了2个新按钮,一个“下一个”按钮和一个“上一个”按钮。现在,它们仅在突出显示事件时才起作用,但是我希望它向下滚动到找到的下一个或上一个文本事件(就像按键盘上的f3时一样)我该怎么做?

以下是我的代码:

    <script
  src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
  integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
  crossorigin="anonymous"></script>

<pre>
<div class="SearchButtonsSection">

          <input name="text-12" id="text-12" value="" type="text" class="txtSearch">
          <button><a href="#" class="search btn">Search</a></button>
          <button><a href="#" class="next btn">Next</a></button>
          <button><a href="#" class="previous btn">Previous</a></button>
    </div>

        <div id="content" style="with:100%">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in felis ut dui dictum cursus. In at congue dui. Fusce sit amet ligula faucibus, tincidunt ligula nec, elementum dolor. Integer dignissim tellus vitae ligula egestas, laoreet dictum mauris laoreet. Nulla lorem turpis, hendrerit quis urna ut, bibendum hendrerit elit. Sed non lorem tincidunt, viverra purus fringilla, dignissim mauris. Phasellus ac pellentesque enim. Fusce et mattis nibh. Maecenas non imperdiet nisi, lobortis consequat mauris. Etiam suscipit odio vitae interdum cursus. Aliquam ut rhoncus metus. Donec sed malesuada augue, eu interdum orci. Vestibulum porta lobortis orci a maximus. Etiam id tellus eleifend, condimentum nisi ac, lobortis ante. Nullam nec libero porttitor, dictum lacus sit amet, faucibus nulla.

Maecenas scelerisque posuere sem sed auctor. Ut eget dapibus diam, molestie eleifend est. In interdum lacus vitae ullamcorper convallis. Sed nec felis vitae lacus rhoncus suscipit commodo eget diam. Phasellus tincidunt, turpis vel ultricies cursus, massa est egestas mi, ut faucibus velit neque nec dui. Suspendisse potenti. Phasellus rhoncus, felis a sagittis condimentum, quam purus mattis urna, id ullamcorper dui mauris id nisl. Donec bibendum a nunc at hendrerit. In porttitor turpis at lorem tincidunt venenatis. Mauris mattis dolor sed libero iaculis, quis mattis dui ornare. Nullam euismod, metus vel blandit viverra, ipsum elit fermentum felis, eu facilisis nisi mi non nisl. Integer enim erat, feugiat eget consectetur non, dapibus id nisi </p></div>



<style>

 .highlighted {
     background-color:yellow;
 }
 .highlight {
     background-color: #fff34d;
     -moz-border-radius: 5px;
     /* FF1+ */
     -webkit-border-radius: 5px;
     /* Saf3-4 */
     border-radius: 5px;
     /* Opera 10.5, IE 9, Saf5, Chrome */
     -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7);
     /* FF3.5+ */
     -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7);
     /* Saf3.0+, Chrome */
     box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7);
     /* Opera 10.5+, IE 9.0 */
 }
 .highlight {
     padding:1px 4px;
     margin:0 -4px;
 }

    .searchBtns{
        height:20px;
        width:100px;
        border: 1px solid black;
        float:left;
        margin-bottom: 20px;
        text-decoration: none;
    }
    .SearchButtonSection{
        height:300px;
        width:100%;

    }

    a {
        text-decoration: none;
        color:black;
    }

    .button{
        float:right;
        margin-left:50px;
    }
</style>


<script>
function searchAndHighlight(searchTerm, selector) {
    if (searchTerm) {
        //var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
        //var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
        var selector = selector || "#content"; //use body as selector if none provided
        var searchTermRegEx = new RegExp(searchTerm, "ig");
        var matches = $(selector).text().match(searchTermRegEx);
        if (matches != null && matches.length > 0) {
            $('.highlighted').removeClass('highlighted'); //Remove old search highlights  

            //Remove the previous matches
            $span = $('#content span');
            $span.replaceWith($span.html());

    if (searchTerm === "&") {
        searchTerm = "&amp;";
        searchTermRegEx = new RegExp(searchTerm, "ig");
    }
            $(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + searchTerm + "</span>"));
            $('.match:first').addClass('highlighted');

            var i = 0;

            $('.next').off('click').on('click', function () {
                i++;

                if (i >= $('.match').length) i = 0;

                $('.match').removeClass('highlighted');
                $('.match').eq(i).addClass('highlighted');
                $('.ui-mobile-viewport').animate({
                    scrollTop: $('.match').eq(i).offset().top
                }, 300);
            });
            $('.previous').off('click').on('click', function () {

                i--;

                if (i < 0) i = $('.match').length - 1;

                $('.match').removeClass('highlighted');
                $('.match').eq(i).addClass('highlighted');
                $('.ui-mobile-viewport').animate({
                    scrollTop: $('.match').eq(i).offset().top
                }, 300);
            });




            if ($('.highlighted:first').length) { //if match found, scroll to where the first one appears
                $(window).scrollTop($('.highlighted:first').position().top);
            }
            return true;
        }
    }
    return false;
}

$(document).on('click', '.search', function (event) {

    $(".highlighted").removeClass("highlighted").removeClass("match");
    if (!searchAndHighlight($('.txtSearch').val())) {
        alert("No results found");
    }


});
</script>


<script>
function searchAndHighlight(searchTerm, selector) {
    if (searchTerm) {
        //var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
        //var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
        var selector = selector || "#content"; //use body as selector if none provided
        var searchTermRegEx = new RegExp(searchTerm, "ig");
        var matches = $(selector).text().match(searchTermRegEx);
        if (matches != null && matches.length > 0) {
            $('.highlighted').removeClass('highlighted'); //Remove old search highlights  

            //Remove the previous matches
            $span = $('#content span');
            $span.replaceWith($span.html());

    if (searchTerm === "&") {
        searchTerm = "&";
        searchTermRegEx = new RegExp(searchTerm, "ig");
    }
            $(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + searchTerm + "</span>"));
            $('.match:first').addClass('highlighted');

            var i = 0;

            $('.next').off('click').on('click', function () {
                i++;

                if (i >= $('.match').length) i = 0;

                $('.match').removeClass('highlighted');
                $('.match').eq(i).addClass('highlighted');
                $('.ui-mobile-viewport').animate({
                    scrollTop: $('.match').eq(i).offset().top
                }, 300);
            });
            $('.previous').off('click').on('click', function () {

                i--;

                if (i < 0) i = $('.match').length - 1;

                $('.match').removeClass('highlighted');
                $('.match').eq(i).addClass('highlighted');
                $('.ui-mobile-viewport').animate({
                    scrollTop: $('.match').eq(i).offset().top
                }, 300);
            });




            if ($('.highlighted:first').length) { //if match found, scroll to where the first one appears
                $(window).scrollTop($('.highlighted:first').position().top);
            }
            return true;
        }
    }
    return false;
}

$(document).on('click', '.search', function (event) {

    $(".highlighted").removeClass("highlighted").removeClass("match");
    if (!searchAndHighlight($('.txtSearch').val())) {
        alert("No results found");
    }


});
</script>

1 个答案:

答案 0 :(得分:2)

我通过替换来使其正常工作

require __DIR__.'/bootstrap/autoload.php';

$app = require_once __DIR__.'/bootstrap/start.php';

具有:

$('.ui-mobile-viewport').animate({scrollTop: $('.match').eq(i).offset().top}, 300);

由于某些原因jsfiddle无法识别该功能,因此我没有测试它是否可以进行动画处理,但是似乎出现了问题,您正在尝试滚动一个没有$(window).scrollTop($('.match').eq(i).offset().top); 的元素,因此它展开使窗口可以滚动。因此,请滚动窗口或在容器中设置overflow: auto

相关问题