简体   繁体   English

在javascript中自动跳转,有可能吗?

[英]auto jump in javascript, is it possible?

I am working on a project. 我正在做一个项目。 You as a user are able to "add" input fields, however if you add too many input fields you will (of course) get a scrollbar. 您作为用户可以“添加”输入字段,但是如果添加太多输入字段,您(当然)将获得滚动条。

It would be quite annoying to scroll all the way down to write something in an input field that's somewhere all the way down. 一直向下滚动以在输入字段中写入某些东西一直都是非常烦人的。

Here is a jsfiddle so you get a better idea of what I mean. 这是一个jsfiddle,所以你可以更好地了解我的意思。

At first I thought maybe this could be done with autofocus, but (as far as I know) autofocus only focusses the input field. 起初我想也许这可以通过自动对焦完成,但(据我所知)自动对焦只关注输入字段。

I have been looking around and even read the API of javascript (in hopes of maybe encountering something similar would pop up), but I didn't find any. 我一直在环顾四周,甚至阅读javascript的API(希望可能遇到类似的东西会弹出),但我没有找到任何。

$(document).ready(function() {
  var id = 0;
  var addOpdracht = $('<a/>', {
    'class': 'btn btn-success',
    'id': 'addOpdracht'
  }).on('click', function() {
    $('form').append(getExerciseBlock(id));
    id++;
  }).html('<i class="fa fa-plus fa-2x"></i>');

  $('form').append(addOpdracht);
  $('form').append(getExerciseTitle());
})



function getAddBtn(target, i) {
  var addBtn = $('<a/>', {
    'class': 'btn btn-primary',
    'id': 'addBtn'
  }).on('click', function() {
    $(target).append(getWordPartInput(i));
  }).html('<i class="fa fa-plus"></i>');
  console.log(target);
  return addBtn;
}

function getRemoveBtn(target, i) {
  var RemoveBtn = $('<a/>', {
    'class': 'btn btn-danger'
  }).on('click', function() {
    let syllableInputs = $(this).parent().children("input.syllable");
    syllableInputs[syllableInputs.length - 1].remove(target);
  }).html('<i class="fa fa-minus"></i>');

  return RemoveBtn;
}



function getExerciseBlock(i) {
  var eBlock = $('<div/>', {
    'id': i,
    'class': 'col-md-12 eBlock'
  });

  $(eBlock).append(getAudioBtn(i), getWordInput(i), getWordPartInput(i), getWordPartInput(i), getRemoveBtn(i), getAddBtn(eBlock, i));

  return eBlock;
}


function getAudioBtn(id, cValue) {
  cValue = cValue || '';
  var audioBtn = $('<a/>', {
    'class': 'btn btn-primary'
  }).html('<i class="fa fa-volume-up"></i>');
  return audioBtn;
}


function getWordInput(id, cValue) {
  cValue = cValue || '';
  var wInput = $('<input/>', {
    'class': 'exerciseGetWordInput form-group form-control',
    'type': 'text',
    'name': 'question_takeAudio_exerciseWord[]',
    'placeholder': 'Exercise',
    'id': 'exerciseGetWordInput'
    //'value': ' + response.main_object.exercises[i].exerciseGetWordInput + '
  })
  return wInput;
}


function getWordPartInput(id, cValue) {
  cValue = cValue || '';
  var wpInput = $('<input/>', {
    'class': 'form-group form-control syllable',
    'type': 'text',
    'value': cValue,
    'placeholder': 'Syllables',
    'id': 'SyllablesGetWordPartInput'
  });
  return wpInput;
}

function getExerciseTitle() {
  var exerciseTitle = $('<input/>', {
    'class': 'getExerciseTitle form-group form-control required',
    'type': 'text',
    'name': 'getExerciseTitle',
    'id': 'getExerciseTitle',
    'placeholder': 'Exercise title',
    'required': true
  });

  return exerciseTitle;
}


function getResetInputs() {
  location.reload();
}
<div class="container">
  <div class="panel-group">
    <div class="panel panel-default">
      <div class="panel panel-primary">
        <div class="panel-heading">
          <div class="row">
            <h2 id="exerciseTitleCMS" class="col-md-8 col-sm-7 col-xs-6">Content Managment System</h2>
            <div class="col-md-offset-2 col-md-2">
              <h2>
                <select class="languageSelector form-control required" id="languageSelector"></select>
              </h2>
            </div>
          </div>
        </div>
        <!-- end of panel-heading -->
        <div class="panel-body">
          <div class="jumbotron" id="mainList">
            <form id='my_form' class="container-fluid" action="#" method="POST" required>
              <button id='resetInputs' type='button' onclick='getResetInputs()' class='btn btn-danger fa fa-refresh fa-2x resetInputs'></button>
              <button type='submit' id='saveBtn' class='btn btn-info fa fa-download fa-2x saveBtn' required></button>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

I would like to know: 我想知道:
Is there a certain keyword that makes the autofocus (or in my case, the jump to the last added element) and if so, how should this be implemented? 是否有某个关键字使自动对焦(或者在我的情况下,跳转到最后添加的元素),如果是,应该如何实现? EDIT: my "exercise input field" should be focussed only, not the syllables... And when I click the add button to add a new block (in the fiddle click the big + sign next to the download button), it stops focussing the new added element. 编辑:我的“运动输入字段”应该只关注,而不是音节...当我点击添加按钮添加一个新的块(在小提琴点击下载按钮旁边的大+符号),它停止聚焦新添加的元素。 Therefore I don't exactly think this is a duplicate of the question asked, he only needs one autofocus and that's it. 因此,我并不认为这是问题的重复,他只需要一个自动对焦,就是这样。 I need mine to be focussed on the new added input element. 我需要将我的注意力集中在新添加的输入元素上。

Here is how you can do this. 是你如何做到这一点。

Here's a complete solution: 这是一个完整的解决方案:

 var cursorFocus = function(elem) { var cursorFocus = function(elem){\n    var x = window.scrollX, y = window.scrollY; var x = window.scrollX,y = window.scrollY;\n    elem.focus(); elem.focus();\n    window.scrollTo(x, y); window.scrollTo(x,y);\n} } 
\ncursorFocus(document.getElementById('search-terms')); cursorFocus(的document.getElementById( '搜索术语'));

The principle is quite simple. 原理很简单。 Except of focusing you need to scroll to that element. 除了聚焦之外,您需要滚动到该元素。

EDIT 编辑

For OP: 对于OP: 在此输入图像描述

There are many elements with the same id, so don't say there are not. 有许多具有相同id的元素,所以不要说没有。

This is not the way to go. 这不是要走的路。

Anyway after you create input (on plus icon click) you should give it an unique id or class and then you can use the solution above using function like this 无论如何,在你创建输入(加上图标点击)后你应该给它一个唯一的id或类,然后你可以使用上面的解决方案使用这样的功能

cursorFocus(document.getElementById('your_unique_id'));

or 要么

cursorFocus(document.getElementsByClassName('your_unique_classname')[0]);

EDIT2 EDIT2

It was just qoutation, it wasn't my solution. 这只是个问题,这不是我的解决方案。 But here is a quick fix. 但这是一个快速解决方案。

Instead of 代替

var x = window.scrollX, y = window.scrollY;

Do

var x = elem.scrollX, y = elem.getBoundingClientRect().top + window.scrollY;

Here is fiddle for what you want FIDDLE 这是你想要的FIDDLE的小提琴

You will notice that I have added the focus and select function in the click even 你会注意到我已经在点击中添加了焦点和选择功能

$(document).ready(function() {
  var id = 0;
  var addOpdracht = $('<a/>', {
    'class': 'btn btn-success',
    'id': 'addOpdracht'
  }).on('click', function() {
    $('form').append(getExerciseBlock(id));
    $(".exerciseGetWordInput_" + id).focus().select(); /// I also changed the class a little to make it unique
    id++;
  }).html('<i class="fa fa-plus fa-2x"></i>');

  $('form').append(addOpdracht);
  $('form').append(getExerciseTitle());
});

In the function 在功能

function getWordInput(id, cValue) {
  cValue = cValue || '';
  var wInput = $('<input/>', {
    'class': 'exerciseGetWordInput_' + id + ' form-group form-control',  // changed the class name here
    'type': 'text',
    'name': 'question_takeAudio_exerciseWord[]',
    'placeholder': 'Exercise',
    'id': 'exerciseGetWordInput'
  })
  return wInput;
}

See how I have added the unique class name. 看看我如何添加唯一的类名。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM