Мы извлекаем текст [Text1 и Text2] из JSON и отображаем на странице. Как только пользователь нажимает на текст, мы отображаем всплывающее окно....
Требование :
Я хочу отобразить все шрифты Google во всплывающем окне в раскрывающемся списке....
Проблема :
Шрифты Google отображаются за пределами всплывающего окна, а не внутри....
Логика :
Какой бы код я ни написал внутри тега шаблона, он должен отображаться внутри всплывающего окна.... но здесь он отображается снаружи....
<template id='template2'>
<input type = "range" min = "40" max = "80" oninput = "fontRange(this)"
<script>
$(function() {
$('#font').fontselect().change(function() {
// replace + signs with spaces for css
var font = $(this).val().replace(/\+/g, ' ');
// split font into family and weight
font = font.split(':');
// set family on paragraphs
$('p').css('font-family', font[0]);
});
});
</script>
</template>
сценарий
$('.container').append(
'<div id = "font"><a id = "' + layer.name + '" onclick = "openPopUp(' + lightId + ')"' +
'<div class = "txtContainer" id = "text" contenteditable = "true" ' +
'style = "' +
'left: ' + layer.x + 'px; ' +
'top: ' + layer.y + 'px; ' +
'font-size: ' + layer.size + 'px; ' +
'">' + layer.text + '</div></a></div> ' +
'<div id = "light' + layer.name + '" class = "white_content" style = "' +
'left: ' + layer.x + 'px; ' +
'top: ' + layer.y + 'px; ' + '"> ' +
$('#template2').html() +
'<a href = "javascript:void(0)" onclick = "closePopUp(' + lightId + ')">Close</a></div> <div>'
);
Кодовое слово: https://codepen.io/kidsdial/pen/NmyPKN
Ниже приведен фрагмент кода:
//font color
var className;
function changeColor(data) {
var color = $(data).css('background-color');
var changeColor = $(className).css('color', color);
}
//font color end
// Display pop up next to text
function closePopUp(el) {
el.style.display = 'none';
openID = null
}
function openPopUp(el) {
///console.info(" open is called ",id)
if (openID != null) {
closePopUp(openID)
}
//font color
var colorID = el.id.substring(5);
className = '#' + colorID;
//font color end
el.style.display = 'block';
openID = el;
}
function fontRange(e) {
var element = e.parentElement.id;
element = "#edit_" + element.split("_")[1];
$(element).css('font-size', e.value + 'px');
}
let openID = null;
var target;
var imageUrl = "https://i.imgur.com/RzEm1WK.png";
let jsonData = {
"layers":[
{
"x":0,
"height":612,
"layers":[
{
"x":160,
"layers":[
{
"font":"Montserrat-Bold",
"x":36,
"y":63,
"width" : 801,
"height" : 371,
"type":"text",
"src" : "a7bde03063d9fc0ef14eecd18f7eba31_Font522.otf",
"size":60,
"text":"Text1",
"name":"edit_mayer"
}
],
"y":291,
"name":"user_image_1"
},
{
"x":25,
"layers":[
{
"font":"Montserrat-Bold",
"x":136,
"y":163,
"width" : 801,
"height" : 371,
"src" : "a7bde03063d9fc0ef14eecd18f7eba31_Font522.otf",
"type":"text",
"size":60,
"text":"Text2",
"name":"edit_sale"
}
],
"y":22,
"name":"L2"
}
],
"y":0,
"width":612,
"name":"L1"
}
]
};
$(document).ready(function() {
// Below code will fetch text from json file
function getAllSrc(layers) {
let arr = [];
layers.forEach(layer => {
if (layer.src) {
arr.push({
src: layer.src,
x: layer.x,
y: layer.y,
height: layer.height,
width: layer.width,
name: layer.name
});
} else if (layer.layers) {
let newArr = getAllSrc(layer.layers);
if (newArr.length > 0) {
newArr.forEach(({
src,
x,
y,
height,
width,
name
}) => {
arr.push({
src,
x: (layer.x + x),
y: (layer.y + y),
height,
width,
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');
var mask = $(".container").mask({
imageUrl: imageUrl,
maskImageUrl: 'http://piccellsapp.com:1337/parse/files/PfAppId/' + src,
onMaskImageCreate: function(img) {
// Mask image positions
img.css({
"position": "absolute",
"left": x + "px",
"top": y + "px"
});
// end
},
id: counter
});
table.push(mask);
fileup.onchange = function() {
let mask2 = table[target];
const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
document.getElementById('fileup').value = "";
};
counter++;
}
drawText(data);
}
json(jsonData);
}); // end of document ready
const fonts = []; // caching duplicate fonts
// Text code
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(
'<input id = "font" style = "display:none"><a id = "' + layer.name + '" onclick = "openPopUp(' + lightId + ')"' +
'<div class = "txtContainer" id = "text" 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; ' + '"> ' +
$('#template2').html() +
'<a href = "javascript:void(0)" onclick = "closePopUp(' + lightId + ')">Close</a></div> <div>'
);
document.getElementById(lightId).style.left = layer.x + document.getElementById(layer.name).offsetWidth + 'px'
// Above is POP UP Code
}
}
// extempl code end
// jq plugin
(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();
};
});
};
function renderInnerImage() {
img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = settings.imageUrl;
img.onload = function() {
settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
context.globalCompositeOperation = 'source-atop';
context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
initImage = false;
};
}
// change the draggable image
container.loadImage = function(imageUrl) {
console.info("load");
//if (img)
// img.remove();
// reset the code.
settings.y = startY;
settings.x = startX;
prevX = prevY = 0;
settings.imageUrl = imageUrl;
initImage = true;
container.updateStyle().then(renderInnerImage);
// sirpepole Add this
return settings.id;
};
};
}(jQuery));.container {
background: silver;
position: relative;
}
.container img {
position: absolute;
top: 0;
bottom: 250px;
left: 0;
right: 0;
margin: auto;
z-index: 999;
}
.txtContainer {
position: absolute;
text-align: center;
color: #FFF
}
.txtContainer:hover {
background: red;
padding: 1px;
border-style: dotted;
}
.pip {
display: inline-block;
margin: 0;
position: absolute;
}
.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;
}
.radiobutton {
display: inline-block;
position: relative;
width: 50px;
height: 50px;
margin: 10px;
cursor: pointer;
}
.radiobutton span {
display: block;
position: absolute;
width: 50px;
height: 50px;
padding: 0;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
border-radius: 100%;
background: #eeeeee;
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
transition: ease .3s;
}
.radiobutton span:hover {
padding: 10px;
}
.orange .radiobutton span {
background: #FF5722;
}
.red .radiobutton span {
background: #FFC107;
}
.radiocolor {
display: block;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: transparent;
/*transition: ease .3s;*/
z-index: -1;
}<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel = "stylesheet" type = "text/css" href = "https://www.jqueryscript.net/demo/Easy-Google-Web-Font-Selector-With-jQuery-Fontselect/fontselect.css" />
<script src = "https://www.jqueryscript.net/demo/Easy-Google-Web-Font-Selector-With-jQuery-Fontselect/jquery.fontselect.js"></script>
<input id = "fileup" name = "fileup" type = "file" style = "display:none" >
<div class = "container"></div>
<template id='template2'>
<input type = "range" min = "10" max = "40" oninput = "fontRange(this)" onchange = "fontRange(this)">
<label class = "orange">
<input type = "radio" name = "color" value = "orange" style = "display:none" >
<div class = "radiocolor"></div>
<div class = "radiobutton"><span onclick = "changeColor(this)"></span></div>
</label>
<label class = "red">
<input type = "radio" name = "color" value = "red" style = "display:none" >
<div class = "radiocolor"></div>
<div class = "radiobutton"><span onclick = "changeColor(this)"></span></div>
</label>
<script>
$(function() {
$('#font').fontselect().change(function() {
// replace + signs with spaces for css
var font = $(this).val().replace(/\+/g, ' ');
// split font into family and weight
font = font.split(':');
// set family on paragraphs
$('p').css('font-family', font[0]);
});
});
</script>
</template>


![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Посетите этот codepen, который я сделал для вас https://codepen.io/anon/pen/dLmpeL
где я добавил глобальный класс с именем className и добавил его идентификатор в className.
теперь я получаю значение стиля всплывающего окна и добавляю его в раскрывающийся список и добавляю несколько пикселей, чтобы выглядеть красиво
var styleTop = el.style.top;
var styleLeft = el.style.left;
styleTop = parseInt(styleTop.substring(3 , -1)) + 130;
styleLeft = parseInt(styleLeft.substring(3 , -1)) + 30;
console.info(styleTop);
console.info(styleLeft);
$('.font-select:first').css({
display: 'block',
left: styleLeft + 'px',
top: styleTop + 'px',
zIndex: 1010
});
Надеюсь, вам понравится.
пожалуйста, дайте мне причину для понижения, так что я исправлю это .....