在箭头键上移动HTML对象按

时间:2017-06-09 10:12:23

标签: javascript php jquery keydown

我想浏览div内容(带有属性id="brand_div"的div),同时按下上下键按下。

<input type="text" autocomplete="off" name="brand_search_box"  id="brand_searchterm" placeholder="Select Your Brand">


<div id="brand_div" class="c_result" style="display: block;">
<a class="brand_sugg" href="#">
<div class="c_result show">Medicine</div>
</a>

<a class="brand_sugg" href="#">
<div class="c_result show">sandals</div>
</a>

<a class="brand_sugg" href="#">
<div class="c_result show">Dress</div>
</a>
</div>

// OnkeyUp Code

 $('#brand_searchterm').on('keyup', function (e) {

        var key = $('#brand_searchterm').val();
        if (key)
        {
            if (req)
                req.abort();
                req = $.ajax({
                url: "<?php echo base_url() ?>home/brand_search_sugg",
                type: 'POST',
                cache: false,
                data: {
                    brand_search: key
                },
                success: function (data)
                {
                    if (data)
                    {   
                        $('#loading').css('display', 'none');
                        $("#brand_div").html(data).show();
                        if($('#brand_div a:focus').length==0){$('#brand_div a').first().focus();}
                        if (e.keyCode == 40) 
                        {   
                            $("#brand_div a:focus").next().focus();
                        } 
                        if(e.keyCode==38)
                        {           
                           $("#brand_div a:focus").prev().focus();
                        }                           
                    }
                }

            });
        } 
    });

这段代码工作得很完美..但是当我每次窗口的滚动条向下移动时单击向下箭头键,当我按下键盘时滚动条向上滚动.....

1 个答案:

答案 0 :(得分:0)

window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
}, false);

当用户按向上或向下箭头时,此代码将避免滚动页面。

或者您可以在滚动高度上调用AJAX。

如果服务返回的数据为空,您可以导航到下一个div。

$(document).scroll(function(e){

    // grab the scroll amount and the window height
    var scrollAmount = $(window).scrollTop();
    var documentHeight = $(document).height();

    // calculate the percentage the user has scrolled down the page
    var scrollPercent = (scrollAmount / documentHeight) * 100;

    if(scrollPercent > 50) {
        // run a function called doSomething
       doSomething();
    }

    function doSomething() { 

        // do something when a user gets 50% of the way down my page

    }

});