简体   繁体   中英

Get height of the input inside div scroll - javascript

I have inputs inside div overflow scroll. JSFIDDLE

Here when i click tab i should be able to get the height of that input.

First input : height 10px; - clicked tab

Second input : height 20px;

I have the properties of activeElement

nextInput   {...}   [Object, HTMLInputElement]
[Methods]   {...}   er
clientTop   2   Number
clientWidth 562 Number
COMMENT_NODE    8   Number
complete    false   Boolean         
ng339   742 Number
nodeName    "INPUT" String
scrollHeight    46  Number
scrollLeft  0   Number
scrollTop   0   Number
scrollWidth 562 Number
selectionEnd    0   Number
selectionStart  0   Number
size    20  Number      
willValidate    false   Boolean

How to achieve this?

To calculate the distance of the element from the top of the div (after scrolling), you need to use the scrollTop property of the div and the offsetTop property of the input element. Assuming you have a reference to these elements, you make the calculation like this:

var currentPosition = inputElement.offsetTop - divElement.scrollTop;

In order to do calculate the distance that each element is from the top of its parent, you're looking for .offsetTop .

In the following example, I do this by looping over getElementsByTagName() :

 var elements = document.getElementsByTagName('input'); for (var i = 0; i < elements.length; i++) { elements[i].onclick = function() { console.log(this.offsetTop); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div style="max-height:80px;overflow:auto;width:210px;"> <input type="text" style="height:10px"> <input type="text" style="height:20px"> <input type="text" style="height:30px"> <input type="text" style="height:20px"> </div> 

Note that .offsetTop only works on the immediate parent. If you'd like to calculate the distance from an element higher up in the DOM, you'll need to loop through all available parents and sum up their offsets.

Hope this helps! :)

i got solution @Matarishvan

here is my code you just need to use focus event and fetch height of that element

<div >
   <form>
      <input type="text" placeholder="first input"></input>
      <input id="secondtext" type="text" placeholder="second text"></input>
   </form>
</div>

<script>

$(document).ready(function () {
    $("input").hover(function(){
      var val = $(this).height();
      console.log(val);
    });
})
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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