使用javascript调整图像大小

时间:2018-02-14 12:57:15

标签: javascript html css

我正在测试使用javascript调整图像大小。我正在使用 Flask ,我的 htlm 代码如下:

    {% extends "base.html" %}
    {% import "bootstrap/wtf.html" as wtf %}
    {% block title %} - Home{% endblock %}
    {% block page_content %}

        <div class="page-header">
            <h1> Rubbish bags collected since 2016 </h1>
        </div>

        <div>
            <img id="rubbish" src="{{ url_for('.fig') }}" alt="Rubbish bags">
        </div>

        <p>Click the button to get the ID of the image.</p>

        <button onclick="myFunction()">Try it</button>

        <p id="demo"></p>

     {% endblock %}
     {% block scripts %}
     {{ super() }}
     {% endblock %}

图像由 Flask视图功能生成。用于检查图像ID的 &#34; myFunction()&#34; 功能如下:

    function myFunction() {
        var x = document.getElementById('rubbish').id;
        document.getElementById('demo').innerHTML = x;
    }

当我点击&#34; myFunction()&#34; 时,ID图像的结果为&#34; 垃圾&#34; ,正如所料。但是,当我尝试通过更改窗口大小来访问图像以使用 属性更改 时,没有任何反应。这是javascript代码:

    $(function() {
        if($(window).width() < 500)
        var parentwith = $('rubbish').parent().css('width');
    $('rubbish').css('width', parentwith);
    });

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

似乎你正在使用jQuery,所以要通过你需要添加#的id来定位一个元素,你也可以使用jQuery resize函数来了解windows resize事件。

&#13;
&#13;
function myFunction() {
    var x = document.getElementById('rubbish').id;
    document.getElementById('demo').innerHTML = x;
}
    
$(window).resize(function() {
    if($(window).width() < 500) {
        var parentwith = $('#rubbish').parent().css('width');
        $('#rubbish').css('width', parentwith);
    }
});
&#13;
#rubbish {
  width:100px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page-header">
    <h1> Rubbish bags collected since 2016 </h1>
</div>

<div>
    <img id="rubbish" src="http://via.placeholder.com/350x150" alt="Rubbish bags">
</div>

<p>Click the button to get the ID of the image.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
&#13;
&#13;
&#13;

您可以使用Js调整图像大小,但更好的方法是使用媒体查询使用纯css或使用百分比宽度进行此操作。

答案 1 :(得分:0)

if($(window).width() < 500)
    var parentwith = $('rubbish').parent().css('width'); // Should be  $('#rubbish')

// If window's width is >= 500, here you'll get a "parentwith is undefined" error
$('rubbish').css('width', parentwith); 

但为什么要将Javascript(document.getElementById('rubbish'))和jQuery($("#rubbish"))混合在一起?

...但是,为什么要做这一切,只是将图像的宽度设置为与其父图像相同?一个简单的CSS媒体查询可以做同样的事情,并且执行速度更快:

@media (max-width: 500px){
    img#rubbish {
       width : 100%;
    }
}