div顶部的文字标签

时间:2017-07-21 06:52:17

标签: javascript jquery html

我正在尝试在图像顶部添加多个标记针和标签。

以下是jsfiddle代码:https://jsfiddle.net/at3wsepm/

我可以添加标记引脚,但是将标签放在标记顶部(从pinid输入)的最佳方法是什么?

我将标记添加到可拖动的对象数组

var pins = [];

$("#addPin").on("click", function(){
  var elem = $("<div/>").addClass("pin");
  $("#carea").append(elem);
    pins.push(new draggable(elem, updatePins));

});

3 个答案:

答案 0 :(得分:1)

演示:https://jsfiddle.net/at3wsepm/1/

只需添加文字,就像创建图钉一样。让他们成为一个项目;

  var pintitle = $("#pinid").val();
  var elemstr= "<div>  <span  class='txt'>"+pintitle +"</span> </div>";
  var elem = $(elemstr).addClass("pin");

请注意我在span中添加的div。使用CSS调整其位置。

答案 1 :(得分:1)

尝试this,css Content将有效,

.pin:after{
 content: attr(content-after); // this will be set from jquery
}
$("#addPin").on("click", function(){
  var elem = $("<div/>");
  var id =$("#pinid").val(); // get text 
  elem.attr("id",id); 
  elem.addClass("pin");
  elem.attr('content-after',id); // set content-after id which css will catch from that name
  $("#carea").append(elem);
    pins.push(new draggable(elem, updatePins));

});

希望有所帮助,

答案 2 :(得分:1)

你可以简单地创建一个标签和一个文本节点,并将文本节点的值设置为输入的值,并将该标签附加到.pin div中,我已经改变了你的代码,它就像一个魅力

<强> HTML

 <div id="carea" class="carea">
 <div id="pinsid" class="pinsid">

</div>
</div>

<div id="dsip"></div>

<input type="text" required="true" placeholder="Pin ID..." name="pinid" id="pinid">
<input type="button" value="Add Pin" id="addPin" >

<强> CSS

#carea {

    background: #19d223;
    position: relative;
     width: 200px;
    height: 200px;
}

.pin {
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height: 100px;
    background-image:url('https://i.downloadatoz.com/download/icon2/5/f/9/ca21cf4a9f7385a7d55b2efcf2b8c0d3.jpg');
    cursor: move;
}

.pin label{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}

<强> JS

(function ($) {

  var draggable = function(element, updateFunc){
    this.position = {x : 0, y : 0};
    this.element = element;
    var _this = this;
    $(_this.element).draggable({

        stop: function() {

            _this.position.x = _this.element.position().left;
            _this.position.y = _this.element.position().top;
            updateFunc();
          }
    });
    }
  window.draggable = draggable;
}(window.jQuery));



var pins = [];

$("#addPin").on("click", function(){
  var elem = $("<div/>").addClass("pin");
  var label = document.createElement("label");  
   var detailt = document.createTextNode( $('input#pinid').val() );
   label.appendChild( detailt );
  elem.append(label);
  $("#carea").append(elem);

    pins.push(new draggable(elem, updatePins));

});
function updatePins(){
  $("#pinslist ul").empty();
  for(var p in pins){
     var pin = pins[p];

  }
}
//var dd = new draggable(null);

以下是fiddle