在prepend上显示img标签内的左下角四分之一

时间:2018-02-22 14:15:33

标签: javascript jquery html css

我尝试将<img>代码添加到<div> JSFiddle <div id="myDiv"></div> ,但我需要显示其左下角,而不仅仅是完整版。

标记

imgUrl = "nerdist.com/wp-content/uploads/2018/02/oblivion-song-615x346.png"
$('#myDiv').prepend('<img id="theImg" style="width:100%;" src="https://' + imgUrl + '"/>');

的Javascript

/node_modules/keystone/admin/client/App/screens/Item/index.js

可以从图像src中仅显示图像的一部分吗?

3 个答案:

答案 0 :(得分:1)

您不会向img添加背景。将背景添加到div或添加<img src=""

$('#myDiv').prepend('<img id="theImg" src="https://' + imgUrl + '"/>');

这将prepend img代码附加(将其附加到最后一个),然后使用.append()

您可能需要设置此图像的样式以便使用

进行正确对齐
#theImg{
   /* Your CSS here */
}

答案 1 :(得分:0)

试试这个:

$("#mydiv").html("<img id="theImg" src="............" />");

你可以让img标签有它的css预设,或者你可以使用相同的方法在javascript中使用

$("#mydiv").css(...........................);

如果这是您喜欢的方式,那么我会帮助更多。

答案 2 :(得分:0)

要实现您要执行的操作,您需要设置代码样式以调整图像,通过将img定位为relative并使用{{1}来仅显示您想要的季度decalartions。显示四分之一(25%),我们将隐藏(75%)两个方向。

我为您提供了一个实时样本。 查看css,了解数学并根据需要进行修改。请注意,您必须将top and left提供给img-wrapper。没有它,heighttop属性将不起作用。

同时,在您的js代码中,图像不能包含背景图像,而是使用left属性指定图像位置。我希望这能解决你的问题

src
$(document).ready(function() {
    //create the image here
    var img = document.createElement('img');
    
    //listen for load event on the image.
    img.addEventListener('load', function(e) {
        var height = this.offsetHeight,
        width = this.offsetWidth;
        
        var hiddenheight = parseInt(0.75 * height),
        visibleheight = parseInt(0.25 * height),
        hiddenwidth = parseInt(0.75 * width);
        
        $(this).css({
            'top': '-' + hiddenheight + 'px',
            'right': '-' + hiddenwidth + 'px'
        });
        
        $('.img-wrapper').css({
            'max-height': visibleheight + 'px'
        });
    });
    $('.img-wrapper').append(img);
    $(img).attr({
       'src': 'http://fjsfoundations.com/image/global/tile.jpg',
       'alt': 'test image'
    });
});
.img-wrapper {
    overflow: hidden;
    background-color: blue;
    position: relative;
}

.img-wrapper > img {
    display: inline-block;
    height: 100%;
    width: 100%;
    position: relative;
}