显示文本中最后一个单词后弹出

问题描述 投票:0回答:1

背景 :

Onclick Text,我们正在显示Pop Up ....

问题 :

弹出窗口显示在一些随机的地方......

要求:

我希望在完整全文后显示弹出....请以动态的方式帮助我.....

enter image description here

这是小提琴:https://jsfiddle.net/kidsdial1/q1nm3u20/

var target;
var imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {
    "layers": [{
        "x": 0,
        "height": 450,
        "layers": [{
            "x": 0,
            "layers": [{
                    "x": 57,
                    "y": 33,
                    "src": "2ccd95bae3f2a0c8249205ca5dfbed24_Montserrat-Bold.ttf",
                    "type": "text",
                    "size": 67,
                    "text": "First Line",
                    "name": "edit_good"
                },
                {

                    "x": 121,
                    "y": 99,
                    "src": "180ef82d12e3eee668a3f6b51ea444e9_Font972.otf",
                    "type": "text",
                    "size": 67,
                    "text": "Second line",
                    "name": "edit_good_1"
                }
            ],
        }, ],
        "width": 500,
        "name": "L1"
    }]
};

$(document).ready(function() {

    // get the text from json

    function getAllSrc(layers) {
        let arr = [];
        layers.forEach(layer => {
            if (layer.src) {
                arr.push({
                    src: layer.src,
                    x: layer.x,
                    y: layer.y,
                    name: layer.name
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({
                        src,
                        x,
                        y,
                        name
                    }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                            y: (layer.y + y),
                            name: (name)
                        });
                    });
                }
            }
        });
        return arr;
    }

    function json(data)

    {
        var width = 0;
        var height = 0;

        let arr = getAllSrc(data.layers);

        let layer1 = data.layers;
        width = layer1[0].width;
        height = layer1[0].height;
        let counter = 0;
        let table = [];

        for (let {
                src,
                x,
                y,
                name
            } of arr) {
            $(".container").css('width', width + "px").css('height', height + "px").addClass('temp');
            if (name.indexOf('mask_') !== -1) {
                var imageUrl1 = imageUrl;
            } else {
                var imageUrl1 = '';
            }
            var mask = $(".container").mask({
                imageUrl: imageUrl1,
                maskImageUrl: 'http://piccellsapp.com:1337/parse/files/PfAppId/' + src,
                onMaskImageCreate: function(img) {

                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });

                },
                id: counter
            });
            table.push(mask);
            fileup.onchange = function() {

                let mask2 = table[target];
                mask2.loadImage(URL.createObjectURL(fileup.files[0]));
                document.getElementById('fileup').value = "";
            };
            counter++;
            // get the text

        }
        drawText(data);
    }

    json(jsonData);
}); // end of document ready

const fonts = []; // caching duplicate fonts

function drawText(layer) {

    if (layer.type === 'image') return;

    if (!layer.type || layer.type === 'group') {
        return layer.layers.forEach(drawText)
    }

    if (layer.type === 'text') {
        const url = 'http://piccellsapp.com:1337/parse/files/PfAppId/' + layer.src;

        if (!fonts.includes(url)) {
            fonts.push(url);
            $("style").prepend("@font-face {\n" +
                "\tfont-family: \"" + layer.font + "\";\n" +
                "\tsrc: url(" + url + ") format('truetype');\n" +
                "}");
        }

		// Below is POP UP Code
		
		
        $('.container').append(
           
            '<a onclick="document.getElementById(\'light\').style.display=\'block\';document.getElementById(\'fade\').style.display=\'block\'" ' +
  
			'<div class="textcontainer" contenteditable="true" ' +
            'style="' +
            'left: ' + layer.x + 'px; ' + 
            'top: ' + layer.y + 'px; ' + 
            'font-size: ' + layer.size + 'px; ' + 
            '">' + layer.text + '</div></a>'  + 
			'<div id="light" class="white_content"> content <a href="javascript:void(0)" onclick="document.getElementById(\'light\').style.display=\'none\';document.getElementById(\'fade\').style.display=\'none\'">Close</a></div> <div>' 			
			);

    }

}
// extempl code end	

// ignore below code

(function($) {
    var JQmasks = [];
    $.fn.mask = function(options) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            maskImageUrl: undefined,
            imageUrl: undefined,
            scale: 1,
            id: new Date().getUTCMilliseconds().toString(),
            x: 0, // image start position
            y: 0, // image start position
            onMaskImageCreate: function(div) {},
        }, options);


        var container = $(this);

        let prevX = 0,
            prevY = 0,
            draggable = false,
            img,
            canvas,
            context,
            image,
            timeout,
            initImage = false,
            startX = settings.x,
            startY = settings.y,
            div;

        
        container.updateStyle = function() {
            return new Promise((resolve, reject) => {
                context.beginPath();
                context.globalCompositeOperation = "source-over";
                image = new Image();
                image.setAttribute('crossOrigin', 'anonymous');
                image.src = settings.maskImageUrl;
                image.onload = function() {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    context.drawImage(image, 0, 0, image.width, image.height);
                    div.css({
                        "width": image.width,
                        "height": image.height
                    });
                    resolve();
                };
            });
        };              
    };
}(jQuery));
.temp {}

.container {
	background: gold;
  position: relative;
 
}

.white_content {
  display: none;
  position: absolute;
  top: 25%;
  left: 25%;
  width: 50%;
  height: 50%;
  padding: 16px;
  border: 16px solid orange;
  background-color: white;
  z-index: 1002;
  overflow: auto;
}

.masked-img {
	overflow: hidden;	
	position: relative;
}

.textcontainer{ position:absolute;  text-align:center; color:#FFF}

.textcontainer:hover {
     background: red;
     padding: 1px;
	border-style: dotted;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<input id="fileup" name="fileup" type="file" style="display:none" >

<div class="container">

</div>

如果您有任何疑问,请告诉我....

提前致谢....

javascript html css
1个回答
1
投票

您需要将弹出窗口定位为top = layer.y,它是clicked链接的顶部偏移量。并拥有left = layer.width + layer.x

除了非常难以阅读的混乱代码(我不会进入那个)之外,你使用相同的ID(HTML中的NONO)多次追加div。具体来说,你正在为每一层添加<div id="light"。您不允许在HTML中使用重复的ID(不良做法),并且在此特定情况下会破坏代码。

所以我将layer.name添加到light id。所以我们将拥有唯一的ID(只要图层具有不同的名称)。 <div id="light'+layer.name+'"。也可以在其他任何地方添加它。

然后在附加代码中,您应该使用top为弹出窗口设置layer.y属性。然后,您可以使用单击元素的宽度来设置弹出窗口的left属性。你不能在附加中使用内联样式(如top的情况),因为单击的元素会在弹出窗口的同时附加,所以如果我们尝试在它附加的确切时间获取宽度,则它是未定义的。

无论如何,长篇故事短toplayer.y(在弹出的内联样式)document.getElementById('light'+layer.name).style.left = layer.x + document.getElementById(layer.name).offsetWidth + 'px'为左侧定位后附加。

编辑:添加功能以在打开一个弹出窗口时关闭另一个弹出窗口

只需隐藏没有打开的id的white_content。我在a标签document.querySelector(\'.white_content:not(' + lightIdString + ')\').style.display=\'none\'中添加了这一行

const lightId = 'light' + layer.name const lightIdString = '#' + lightId

您可以尝试仅使用lightId并在#中直接添加querySelector()

看到这里jsFiddle

或下面的片段

var target;
var imageUrl = "https://i.imgur.com/RzEm1WK.png";

let jsonData = {
  "layers": [{
    "x": 0,
    "height": 450,
    "layers": [{
      "x": 0,
      "layers": [{
          "x": 57,
          "y": 33,
          "src": "2ccd95bae3f2a0c8249205ca5dfbed24_Montserrat-Bold.ttf",
          "type": "text",
          "size": 67,
          "text": "First Line",
          "name": "edit_good"
        },
        {

          "x": 121,
          "y": 99,
          "src": "180ef82d12e3eee668a3f6b51ea444e9_Font972.otf",
          "type": "text",
          "size": 67,
          "text": "Second line",
          "name": "edit_good_1"
        }
      ],
    }, ],
    "width": 500,
    "name": "L1"
  }]
};

$(document).ready(function() {

  // get the text from json

  function getAllSrc(layers) {
    let arr = [];
    layers.forEach(layer => {
      if (layer.src) {
        arr.push({
          src: layer.src,
          x: layer.x,
          y: layer.y,
          name: layer.name
        });
      } else if (layer.layers) {
        let newArr = getAllSrc(layer.layers);
        if (newArr.length > 0) {
          newArr.forEach(({
            src,
            x,
            y,
            name
          }) => {
            arr.push({
              src,
              x: (layer.x + x),
              y: (layer.y + y),
              name: (name)
            });
          });
        }
      }
    });
    return arr;
  }

  function json(data)

  {
    var width = 0;
    var height = 0;

    let arr = getAllSrc(data.layers);

    let layer1 = data.layers;
    width = layer1[0].width;
    height = layer1[0].height;
    let counter = 0;
    let table = [];

    for (let {
        src,
        x,
        y,
        name
      } of arr) {
      $(".container").css('width', width + "px").css('height', height + "px").addClass('temp');
      if (name.indexOf('mask_') !== -1) {
        var imageUrl1 = imageUrl;
      } else {
        var imageUrl1 = '';
      }
      var mask = $(".container").mask({
        imageUrl: imageUrl1,
        maskImageUrl: 'http://piccellsapp.com:1337/parse/files/PfAppId/' + src,
        onMaskImageCreate: function(img) {

          img.css({
            "position": "absolute",
            "left": x + "px",
            "top": y + "px"
          });

        },
        id: counter
      });
      table.push(mask);
      fileup.onchange = function() {

        let mask2 = table[target];
        mask2.loadImage(URL.createObjectURL(fileup.files[0]));
        document.getElementById('fileup').value = "";
      };
      counter++;
      // get the text

    }
    drawText(data);
  }

  json(jsonData);
}); // end of document ready

const fonts = []; // caching duplicate fonts

function drawText(layer) {

  if (layer.type === 'image') return;

  if (!layer.type || layer.type === 'group') {
    return layer.layers.forEach(drawText)
  }

  if (layer.type === 'text') {
    const url = 'http://piccellsapp.com:1337/parse/files/PfAppId/' + layer.src;

    if (!fonts.includes(url)) {
      fonts.push(url);
      $("style").prepend("@font-face {\n" +
        "\tfont-family: \"" + layer.font + "\";\n" +
        "\tsrc: url(" + url + ") format('truetype');\n" +
        "}");
    }

    // Below is POP UP Code
    const lightId = 'light' + layer.name
    const lightIdString = '#' + lightId


    $('.container').append(

      '<a id ="' + layer.name + '" onclick="document.getElementById(\'' + lightId + '\').style.display=\'block\';document.querySelector(\'.white_content:not(' + lightIdString + ')\').style.display=\'none\';document.getElementById(\'fade\').style.display=\'block\'" ' +
      '<div class="textcontainer" contenteditable="true" ' +
      'style="' +
      'left: ' + layer.x + 'px; ' +
      'top: ' + layer.y + 'px; ' +
      'font-size: ' + layer.size + 'px; ' +
      '">' + layer.text + '</div></a>' +
      '<div id="light' + layer.name + '" class="white_content" style="' +
      'left: ' + layer.x + 'px; ' +
      'top: ' + layer.y + 'px; ' + '"> content <a href="javascript:void(0)" onclick="document.getElementById(\'light' + layer.name + '\').style.display=\'none\';document.getElementById(\'fade\').style.display=\'none\'">Close</a></div> <div>'
    );

    document.getElementById(lightId).style.left = layer.x + document.getElementById(layer.name).offsetWidth + 'px'
  }


}
// extempl code end	

// ignore below code

(function($) {
  var JQmasks = [];
  $.fn.mask = function(options) {
    // This is the easiest way to have default options.
    var settings = $.extend({
      // These are the defaults.
      maskImageUrl: undefined,
      imageUrl: undefined,
      scale: 1,
      id: new Date().getUTCMilliseconds().toString(),
      x: 0, // image start position
      y: 0, // image start position
      onMaskImageCreate: function(div) {},
    }, options);


    var container = $(this);

    let prevX = 0,
      prevY = 0,
      draggable = false,
      img,
      canvas,
      context,
      image,
      timeout,
      initImage = false,
      startX = settings.x,
      startY = settings.y,
      div;


    container.updateStyle = function() {
      return new Promise((resolve, reject) => {
        context.beginPath();
        context.globalCompositeOperation = "source-over";
        image = new Image();
        image.setAttribute('crossOrigin', 'anonymous');
        image.src = settings.maskImageUrl;
        image.onload = function() {
          canvas.width = image.width;
          canvas.height = image.height;
          context.drawImage(image, 0, 0, image.width, image.height);
          div.css({
            "width": image.width,
            "height": image.height
          });
          resolve();
        };
      });
    };
  };
}(jQuery));
.temp {}

.container {
  background: gold;
  position: relative;
}

.white_content {
  display: none;
  position: absolute;
  top: 25%;
  left: 25%;
  width: 50%;
  height: 50%;
  padding: 16px;
  border: 16px solid orange;
  background-color: white;
  z-index: 1002;
  overflow: auto;
}

.masked-img {
  overflow: hidden;
  position: relative;
}

.textcontainer {
  position: absolute;
  text-align: center;
  color: #FFF
}

.textcontainer:hover {
  background: red;
  padding: 1px;
  border-style: dotted;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="fileup" name="fileup" type="file" style="display:none">

<div class="container">

</div>

你得到错误Cannot read property 'style' of null",,因为你没有id为fade的元素。你可以解决这个问题。

热门问题
推荐问题
最新问题