设置加载图像的宽度和高度 jQuery

Set width and height of an image loaded with jQuery

我使用 jQuery 在我的网页上加载图像,如下所示:

$(function () {
    $('#mySelect').change(function () {
        var selectedCity = $('#mySelect').val();
        var myLatLng = new google.maps.LatLng(eval(selectedCity).lan, eval(selectedCity).lng);
        venueMap.setCenter(myLatLng);
        image = 'img.png';
        marker = new google.maps.Marker({
            position: myLatLng,
            map: venueMap,
            icon: image
        });
        marker.setMap(venueMap);
    });
});

如何设置图片的宽高?

我试过了 image.width = 100;image.height = 50;(作为 js 语句)没有成功。

根据我的相关 HTML 代码:

....
<body>
        <center>
            <h2>Testing jQuery with Google Maps</h2>
            <br>
            <br>
            <select id="mySelect">
                <option value="Rome">Rome</option>
                <option value="London">London</option>
            </select>
            <br>
            <br>

            <div id="map"></div>
        </center>
    </body>
.....

您可以 select 使用 select 查询的任何元素,例如 $('#image-id').css() 函数用于在特定元素中设置 css 样式。在 css() 函数内部传递值。

$('#map').css({'height':'50px;','width':'50px;'});map 是特定 image 元素的 ID。

$(function () {
    $('#mySelect').change(function () {
        var selectedCity = $('#mySelect').val();
        var myLatLng = new google.maps.LatLng(eval(selectedCity).lan, eval(selectedCity).lng);
        venueMap.setCenter(myLatLng);
        image = 'img.png';
        marker = new google.maps.Marker({
            position: myLatLng,
            map: venueMap,
            icon: image
        });
        marker.setMap(venueMap);
    });


$('#map').css({'height':'50px;','width':'50px;'});
});

对于jQuery,您可以使用道具功能:

$(element).prop('width', 100);
$(element).prop('height', 50);

其中 $(element) 是图像标签的 selector。 prop() 的第一个参数是 property/attribute 的名称,第二个参数是 属性.

的新值

对于纯 JavaScript,您需要 select 元素,然后将 属性 更改为:

document.getElementById('img').width = 100;
document.getElementById('img').height= 50;

其中 'img' 是图像的 ID。您还可以使用替代 select 或 getElementsByClassName 或 getElementsByName。

您可以添加图像的其他属性,如 Google 地图 Documentation

所示
    var image = {
      url: 'image.png',
      // This marker is 20 pixels wide by 32 pixels high.
      size: new google.maps.Size(20, 32),
      // The origin for this image is (0, 0).
      origin: new google.maps.Point(0, 0),
      // The anchor for this image is the base at (0, 32).
      anchor: new google.maps.Point(0, 32)
    };

希望对您有所帮助。