I want to make a mark that can move like a caret in javascript.

Asked 2 years ago, Updated 2 years ago, 137 views

Enter a description of the image here
↑The image looks like this

jquery/jquery-ui is acceptable.

input[type=text] and sample[mark] that informationHow do I retrieve it in the format Sample ?

I was able to mark it and drag it, but I can't behave the same way as a caret that can only be between characters.
You can't even tell which characters are between the markers.

Help me.

javascript jquery jquery-ui

2022-09-30 20:45

1 Answers

I think the difficulty is to get the coordinates (such as and width) for each character entered in input[type="text"], but you can define the following as a generic function that can get coordinates and widths for each character (although I only try Chrome).

(function($){
  $.fn.mapForEachChar=function(callback){
    var$hidden=this.data("mapForEachChar.$hidden");
    if(!$hidden){
      $hidden=$("<div>");
      This.data("mapForEachChar.$hidden",$hidden);
      $hidden.get(0).style=$.extend(
        true, $hidden.get(0).style, getComputedStyle(this.get(0), '')
      );
      $hidden.css({
        position: "absolute", width:0, height:0, overflow: "hidden",
        visibility: "hidden", whiteSpace: "nowrap"
      });
    }
    return(
      $hidden.html(
        $.map(this.val().split(""), function(c){
          return "<span>"+c+"</span>";
        }).join("")
      ) .appendTo( document.body).children().map(callback).get()
    );
  };
}) (jQuery);

This can be used like this.

$(function(){
  varpos=$("#textbox").mapForEachChar(function(){
    return this.offsetLeft;
  });
  console.log(pos);
  varwid=$("#textbox").mapForEachChar(function(){
    return this.offsetWidth;
  });
  console.log(wid);
});

After that, when you drag or retrieve information, you can determine the coordinates.


2022-09-30 20:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.