Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery滚动到元素_Javascript_Jquery_Scroll - Fatal编程技术网

Javascript jQuery滚动到元素

Javascript jQuery滚动到元素,javascript,jquery,scroll,Javascript,Jquery,Scroll,我有这个输入元素: <input type="text" class="textfield" value="" id="subject" name="subject"> 动画不应该太快,应该是流体 我正在运行最新的jQuery版本。我宁愿不安装任何插件,而是使用默认的jQuery功能来实现这一点。假设您有一个id为按钮的按钮,请尝试以下示例: $("#button").click(function() { $([document.documentElement, docum

我有这个
输入
元素:

<input type="text" class="textfield" value="" id="subject" name="subject">
动画不应该太快,应该是流体


我正在运行最新的jQuery版本。我宁愿不安装任何插件,而是使用默认的jQuery功能来实现这一点。

假设您有一个id为
按钮的按钮,请尝试以下示例:

$("#button").click(function() {
    $([document.documentElement, document.body]).animate({
        scrollTop: $("#elementtoScrollToID").offset().top
    }, 2000);
});
我从文章中得到了密码。我已经在下面的例子中进行了测试


$(文档).ready(函数(){
$(“#单击”)。单击(函数(){
$('html,body')。设置动画({
scrollTop:$(“#div1”).offset().top
}, 2000);
});
});
试验

测试2 点击我

jQuery.scrollTo():

我编写了这个轻量级插件,使页面/元素滚动更加容易。它非常灵活,可以传入目标元素或指定的值。也许这会成为jQuery下一个官方版本的一部分,你觉得呢


示例用法:

$('body').scrollTo('#target'); // Scroll screen to target element

$('body').scrollTo(500); // Scroll screen 500 pixels down

$('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down

选项:

$('body').scrollTo('#target'); // Scroll screen to target element

$('body').scrollTo(500); // Scroll screen 500 pixels down

$('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down
scrollTarget:表示所需滚动位置的元素、字符串或数字

偏移量:定义滚动目标上方额外间距的数字

持续时间:确定动画将运行多长时间的字符串或数字

缓和:一个字符串,指示过渡使用哪个缓和函数


complete:动画完成后调用的函数。

使用此简单脚本

if($(window.location.hash).length > 0){
        $('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000);
}

如果在url中找到散列标记,则会将滚动设置为动画到ID。如果未找到散列标记,则忽略脚本。

如果您对平滑滚动效果不太感兴趣,只对滚动到特定元素感兴趣,则不需要使用jQuery函数。Javascript已经涵盖了您的情况:

因此,您所需要做的就是:
$(“选择器”).get(0.scrollIntoView()


之所以使用
.get(0)
,是因为我们希望检索JavaScript的DOM元素,而不是JQuery的DOM元素。

Steve和Peter的解决方案非常有效

但在某些情况下,可能需要将值转换为整数。奇怪的是,
$(“…).offset().top
返回的值有时在
float

用法:
parseInt($(“…”).offset().top)

例如:

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: parseInt($("#elementtoScrollToID").offset().top)
    }, 2000);
});
要显示完整元素(如果当前窗口大小允许):

var元素=$(“#某些#元素”);
var elementHeight=element.height();
var windowHeight=$(window.height();
var offset=Math.min(elementHeight,windowHeight)+element.offset().top;
$('html,body').animate({scrollTop:offset},500);
jQuery(文档).ready(函数($){
$('a[href^=“#“]”).bind('click.smoothscroll',函数(e){
e、 预防默认值();
var target=this.hash,
$target=$(target);
$('html,body').stop().animate({
'scrollTop':$target.offset().top-40
},900,“摆动”,功能(){
window.location.hash=目标;
} );
} );
} );

紧凑版的“动画”解决方案

$.fn.scrollTo = function (speed) {
    if (typeof(speed) === 'undefined')
        speed = 1000;

    $('html, body').animate({
        scrollTop: parseInt($(this).offset().top)
    }, speed);
};

基本用法:
$(“#您的_元素”).scrollTo()

如果只处理滚动到输入元素的操作,则可以使用
focus()
。例如,如果要滚动到第一个可见输入:

$(':input:visible').first().focus();
或类为
的容器中的第一个可见输入。错误

$('.error :input:visible').first().focus();

感谢您指出这一点

这是我使用通用类选择器抽象ID和href的方法

$(函数(){
//要在任何地方使用的通用选择器
$(“.js滚动至”)。单击(函数(e){
//动态获取href
var destination=$(this.attr('href');
//防止href=“#”链接更改URL哈希(可选)
e、 预防默认值();
//设置滚动到目标的动画
$('html,body')。设置动画({
scrollTop:$(目标).offset().top
}, 500);
});
});


在大多数情况下,最好使用插件。认真地我要去。当然还有其他的。但是,请检查他们是否真的避免了您首先需要插件的陷阱——并非所有人都这样做

我已经写了使用插件的原因。简言之,这里支持大多数答案的一句话

$('html, body').animate( { scrollTop: $target.offset().top }, duration );
这是糟糕的用户体验

  • 动画不响应用户操作。即使用户单击、轻触或尝试滚动,它也会继续

  • 如果动画的起点接近目标元素,则动画的速度会非常慢

  • 如果目标元素位于页面底部附近,则无法将其滚动到窗口顶部。然后,滚动动画在中间运动时突然停止

要处理这些问题(和a),您可以使用我的插件。然后,呼叫变为

$( window ).scrollTo( targetPosition );
就这样。当然有

关于目标位置,在大多数情况下,
$target.offset().top
执行此操作。但是请注意,返回的值没有考虑
html
元素上的边框()。如果您需要目标位置在任何情况下都是准确的,最好使用

targetPosition = $( window ).scrollTop() + $target[0].getBoundingClientRect().top;

即使在
html
元素上设置了边框,它也可以工作。

我编写了一个通用函数,可以滚动到jQuery对象、CSS选择器或数值

用法示例:

// scroll to "#target-element":
$.scrollTo("#target-element");

// scroll to 80 pixels above first element with class ".invalid":
$.scrollTo(".invalid", -80);

// scroll a container with id "#my-container" to 300 pixels from its top:
$.scrollTo(300, 0, "slow", "#my-container");
函数的代码:

/**
* Scrolls the container to the target position minus the offset
*
* @param target    - the destination to scroll to, can be a jQuery object
*                    jQuery selector, or numeric position
* @param offset    - the offset in pixels from the target position, e.g.
*                    pass -80 to scroll to 80 pixels above the target
* @param speed     - the scroll speed in milliseconds, or one of the
*                    strings "fast" or "slow". default: 500
* @param container - a jQuery object or selector for the container to
*                    be scrolled. default: "html, body"
*/
jQuery.scrollTo = function (target, offset, speed, container) {

    if (isNaN(target)) {

        if (!(target instanceof jQuery))
            target = $(target);

        target = parseInt(target.offset().top);
    }

    container = container || "html, body";
    if (!(container instanceof jQuery))
        container = $(container);

    speed = speed || 500;
    offset = offset || 0;

    container.animate({
        scrollTop: target + offset
    }, speed);
};
当用户单击带有#主题的输入时,页面应 滚动到页面的最后一个元素,显示一个漂亮的动画。信息技术 应该是一个滚动到底部而不是
// scroll to "#target-element":
$.scrollTo("#target-element");

// scroll to 80 pixels above first element with class ".invalid":
$.scrollTo(".invalid", -80);

// scroll a container with id "#my-container" to 300 pixels from its top:
$.scrollTo(300, 0, "slow", "#my-container");
/**
* Scrolls the container to the target position minus the offset
*
* @param target    - the destination to scroll to, can be a jQuery object
*                    jQuery selector, or numeric position
* @param offset    - the offset in pixels from the target position, e.g.
*                    pass -80 to scroll to 80 pixels above the target
* @param speed     - the scroll speed in milliseconds, or one of the
*                    strings "fast" or "slow". default: 500
* @param container - a jQuery object or selector for the container to
*                    be scrolled. default: "html, body"
*/
jQuery.scrollTo = function (target, offset, speed, container) {

    if (isNaN(target)) {

        if (!(target instanceof jQuery))
            target = $(target);

        target = parseInt(target.offset().top);
    }

    container = container || "html, body";
    if (!(container instanceof jQuery))
        container = $(container);

    speed = speed || 500;
    offset = offset || 0;

    container.animate({
        scrollTop: target + offset
    }, speed);
};
$('#subject').click(function()
{
    $('#submit').focus();
    $('#subject').focus();
});
<style>
  #F > *
  {
    width: 100%;
  }
</style>

<form id="F" >
  <div id="child_1"> .. </div>
  <div id="child_2"> .. </div>
  ..
  <div id="child_K"> .. </div>
</form>

<script>
  $('#child_N').click(function()
  {
    $('#child_N').focus();
    $('#child_N+1').focus();
    ..
    $('#child_K').focus();

    $('#child_N').focus();
  });
</script>
(function($){
    $.fn.animateScroll = function(){
        console.log($('[scroll]'));
        $('[scroll]').click(function(){
            selector = $($(this).attr('scroll'));
            console.log(selector);
            console.log(selector.offset().top);
            $('html body').animate(
                {scrollTop: (selector.offset().top)}, //- $(window).scrollTop()
                1000
            );
        });
    }
})(jQuery);

// RUN
jQuery(document).ready(function($) {
    $().animateScroll();
});

// IN HTML EXAMPLE
// RUN ONCLICK ON OBJECT WITH ATTRIBUTE SCROLL=".SELECTOR"
// <a scroll="#product">Click To Scroll</a>
var $scrollTo = $('#someId'),
inputElem = $('<input type="text"></input>');

$scrollTo.prepend(inputElem);
inputElem.css({
  position: 'absolute',
  width: '1px',
  height: $scrollTo.height()
});
inputElem.focus();
inputElem.remove();
$("a[href^='#']").on("click", function(e) {
  $("html, body").animate({
    scrollTop: $($(this).attr("href")).offset().top
  }, 1000);
  return false;
});

if ($(window.location.hash).length > 1) {
  $("html, body").animate({
    scrollTop: $(window.location.hash).offset().top
  }, 1000);
}
var _scrollToElement = function (selector) {
  try {
    document.querySelector(selector).scrollIntoView({ behavior: 'smooth' });
  } catch (e) {
    console.warn(e);
  }
}

var _scrollToHashesInHrefs = function () {
  document.querySelectorAll("a[href^='#']").forEach(function (el) {
    el.addEventListener('click', function (e) {
      _scrollToElement(el.getAttribute('href'));
      return false;
    })
  })
  if (window.location.hash) {
    _scrollToElement(window.location.hash);
  }
}

_scrollToHashesInHrefs();
import { scrollToElement, scrollWindowToElement } from 'scroll-element'

/* scroll the window to your target element, duration and offset optional */
let targetElement = document.getElementById('my-item')
scrollWindowToElement(targetElement)

/* scroll the overflow container element to your target element, duration and offset optional */
let containerElement = document.getElementById('my-container')
let targetElement = document.getElementById('my-item')
scrollToElement(containerElement, targetElement)
export const scrollToElement = function(containerElement, targetElement, duration, offset) {
  if (duration == null) { duration = 1000 }
  if (offset == null) { offset = 0 }

  let targetOffsetTop = getElementOffset(targetElement).top
  let containerOffsetTop = getElementOffset(containerElement).top
  let scrollTarget = targetOffsetTop + ( containerElement.scrollTop - containerOffsetTop)
  scrollTarget += offset
  scroll(containerElement, scrollTarget, duration)
}

export const scrollWindowToElement = function(targetElement, duration, offset) {
  if (duration == null) { duration = 1000 }
  if (offset == null) { offset = 0 }

  let scrollTarget = getElementOffset(targetElement).top
  scrollTarget += offset
  scrollWindow(scrollTarget, duration)
}

function scroll(containerElement, scrollTarget, duration) {
  let scrollStep = scrollTarget / (duration / 15)
  let interval = setInterval(() => {
    if ( containerElement.scrollTop < scrollTarget ) {
      containerElement.scrollTop += scrollStep
    } else {
      clearInterval(interval)
    }
  },15)
}

function scrollWindow(scrollTarget, duration) {
  let scrollStep = scrollTarget / (duration / 15)
  let interval = setInterval(() => {
    if ( window.scrollY < scrollTarget ) {
      window.scrollBy( 0, scrollStep )
    } else {
      clearInterval(interval)
    }
  },15)
}

function getElementOffset(element) {
  let de = document.documentElement
  let box = element.getBoundingClientRect()
  let top = box.top + window.pageYOffset - de.clientTop
  let left = box.left + window.pageXOffset - de.clientLeft
  return { top: top, left: left }
}
if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {           
    $('#content').animate({
    scrollTop: $("#elementtoScrollToID").offset().top
   }, 'slow');
}
else{
    $('html, body').animate({
    scrollTop: $("#elementtoScrollToID").offset().top
    }, 'slow');
}
<html>
....
<body>
<div id="content">
....
</div>
</body>
</html>
// slide to top of the page
$('.up').click(function () {
    $("html, body").animate({
        scrollTop: 0
    }, 600);
    return false;
});

// slide page to anchor
$('.menutop b').click(function(){
    //event.preventDefault();
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top
    }, 600);
    return false;
});

// Scroll to class, div
$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#target-element").offset().top
    }, 1000);
});

// div background animate
$(window).scroll(function () {

    var x = $(this).scrollTop();

    // freezze div background
    $('.banner0').css('background-position', '0px ' + x +'px');

    // from left to right
    $('.banner0').css('background-position', x+'px ' +'0px');

    // from right to left
    $('.banner0').css('background-position', -x+'px ' +'0px');

    // from bottom to top
    $('#skills').css('background-position', '0px ' + -x + 'px');

    // move background from top to bottom
    $('.skills1').css('background-position', '0% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 1) + 'px, center top');

    // Show hide mtop menu  
    if ( x > 100 ) {
    $( ".menu" ).addClass( 'menushow' );
    $( ".menu" ).fadeIn("slow");
    $( ".menu" ).animate({opacity: 0.75}, 500);
    } else {
    $( ".menu" ).removeClass( 'menushow' );
    $( ".menu" ).animate({opacity: 1}, 500);
    }

});

// progres bar animation simple
$('.bar1').each(function(i) {
  var width = $(this).data('width');  
  $(this).animate({'width' : width + '%' }, 900, function(){
    // Animation complete
  });  
});
var elem = $('#myElement'),
    container = $('#myScrollableContainer'),
    pos = elem.position().top + container.scrollTop() - container.position().top;

container.animate({
  scrollTop: pos
}
var targetOffset = $('#divID').offset().top;
$('html, body').animate({scrollTop: targetOffset}, 1000);
 $('#element-in-parent-frame', window.parent.document).get(0).scrollIntoView();
var targetOffset = $('#elementToScrollTo').offset().top;
$('#DivParent').animate({scrollTop: targetOffset}, 2500);
document.getElementById("element-id").scrollIntoView();
$('body').animate({
    scrollTop: $('#subject').offset().top - $('body').offset().top + $('body').scrollTop()
}, 'fast');
document.querySelector('scrollHere').scrollIntoView({ behavior: 'smooth' })
function scrollTo(selector) {
    document.querySelector(selector).scrollIntoView({ behavior: 'smooth' })
}
subject.onclick = e=> window.scroll({ top: submit.offsetTop, behavior: 'smooth'});
$('html, body').animate({
   scrollTop: $("#div1").offset().top
}, 2000);
function getPageY(id) {
    let elem = document.getElementById(id);
    let box = elem.getBoundingClientRect();
    var body = document.getElementsByTagName("BODY")[0];
    return box.top + body.scrollTop; // for window scroll: box.top + window.scrollY;
}
$("html, body").animate({ scrollTop: getPageY('div1') }, "slow");