javascript - 如果文本显示在容器外部,则隐藏文本

标签 javascript css html

我们正在通过获取 json 来显示文本....

点击文本,我们允许用户添加更多文本....

enter image description here

问题:

添加的文本应该只显示在 container 内,如果文本超出容器,那么它应该隐藏为 this 5 seconds video ,但现在文本显示在容器之外,如下面的代码所示....

let jsonData = {   
    
    "layers": [{
        "x": 0,
        "height": 300,
        "layers": [                      
            {
                "justification": "center",
                "font": "Coustard-Black",
                "x": 190,
                "y": 150,
                "src": "0a7fb3015bb19745da114bc581e96947_Font248.ttf",
                "width": 72,
                "type": "text",
                "color": "red",
                "size": 32,
                "text": "DATE",
                "height": 17,
                "name": "edit_date"
            }
        ],
        "y": 0,
        "width": 300,
        "type": "group",
        "name": "fb_post_4"
    }]
};

const containerElement = $('#container');
const fileUp = $('#fileup');

$(function() {   

    // IGNORE BELOW CODE

    //  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 = [];

        // container dimensions
        containerElement.css('width', width + "px").css('height', height + "px").addClass('temp');
        //end

        for (let {
                src,
                x,
                y,
                name
            } of arr) {
                   
            var imageUrl1 = '';                         
            var mask = $(".container").mask({
                imageUrl: imageUrl1,

                // Fetch Mask images
                maskImageUrl: 'http://piccellsapp.com:1337/parse/files/PfAppId/' + src,
                // end

                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++;
        }

        // Text
        drawText(data);
    }
    json(jsonData);
}); // end of function

// IGNORE ABOVE CODE

//Fetch text

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 = 'https://i.imgur.com/' + 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 text Code
        const lightId = 'light' + layer.name
        const lightIdString = '#' + lightId
        $('.container').append(
            '<input id="font" style="display:none"><a id ="' + layer.name + '" ' +
            '<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; ' + '"> ' +            
            '</div> <div>'
        );            
    }

}
// text 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));
.container {
	background: silver;
	position: relative;
}

.container img {
	position: absolute;
	top: 0;
	bottom: 250px;
	left: 0;
	right: 0;
	margin: auto;
	z-index: 999;
}

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

.txtContainer {
	position: absolute;
	color: #FFF;
	white-space: pre;
}

.txtContainer:hover {
	position: absolute;
	background: red;
	white-space: pre;
}

.pip {
	display: inline-block;
	margin: 0;
	position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

<div id="container"class="container">
</div>

这里是 Codepen

最佳答案

添加overflow: hidden;.container

.container {
    background: silver;
    position: relative;
    overflow: hidden;
}

关于javascript - 如果文本显示在容器外部,则隐藏文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55824840/

相关文章:

javascript - 使用另一个文本框js自动填充文本框

html - 在每页上打印标题 Print.CSS

html - 让 HTML 页面只播放一次 Flash 电影(不是在重新访问时......)

html - 转换的垂直居中无法按预期工作

html - 移动Safari:在绝对定位的容器中看不到高度为100%的图像

html - 仅使用 CSS 切换 Accordion 字形图标

javascript - 理解为什么滚动动画有效

javascript - Angular 1/ui-router - 将函数执行到数据对象中

javascript - 启动重新初始化 jquery 脚本后 Angular 停止工作

php - 将静态 html 菜单转换为 wordpress 动态菜单,保持样式相同