سؤال

مع jQuery ، أقوم بتغيير SRC للصورة عند النقر

$("#thumb li img").click(function() {
var newlinkimage = $(this).attr("src");

newlinkimage = newlinkimage.substring(14,17);

    $("#avant img").attr("src", 'retouche-hr' + newlinkimage + '-a.jpg');
    $("#apres img").attr("src", 'retouche-hr' +newlinkimage + '-b.jpg');

المشكلة هي أن عرض الصورة الجديد يختلف عن القديم. كيف أحصل على العرض الأصلي للصورة الجديدة (مثل السهم الصغير الذي يحصل على ذلك في Dreamweaver

هل كانت مفيدة؟

المحلول

هذه هي طريقة JavaScript العادية للقيام بذلك. يجب أن يكون من السهل دمج هذا في الكود الخاص بك.

var newimage = new Image();
newimage.src = 'retouche-hr' + newlinkimage + '-a.jpg'; // path to image
var width = newimage.width;
var height = newimage.height;

نصائح أخرى

هل كانت الصورة القديمة لها عرض وارتفاع؟ إذا كنت تستخدم $ (Image) .width ("") ، فيجب إعادة ضبط العرض مرة أخرى إلى ما كان عليه قبل تطبيق أي تغييرات عرض عليها (بالمثل للارتفاع). لا أعتقد أن هذا سيعمل مع الصور التي تم تعيين عرضها عبر CSS أو الممتلكات. بعد إعادة ضبط العرض القديم ، يمكنك استخدام .outerwidth () للحصول على عرض الصورة.

تريد الحصول على العرض الحقيقي للصورة قبل تغييرها ، ثم قم بتعيين الصورة الجديدة على هذا العرض. يمكنك القيام بذلك باستخدام $ (IMG) .Load:

var pic_real_width;
var pic_real_height;

$(img).load(function() {
    // need to remove these in of case img-element has set width and height
    $(this).removeAttr("width")
           .removeAttr("height");

    pic_real_width = this.width;
    pic_real_height = this.height;
});

$("#thumb li img").click(function() {
var newlinkimage = $(this).attr("src");

newlinkimage = newlinkimage.substring(14,17);

        $("#avant img").attr("src", 'retouche-hr' + newlinkimage + '-a.jpg').width(pic_real_width);
        $("#apres img").attr("src", 'retouche-hr' +newlinkimage + '-b.jpg').width(pic_real_width);

this code always return Zero '0'

    var newimage = new Image();
    newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; 
    var width = newimage.naturalWidth;
    var height = newimage.naturalHeight;
    alert (width);

WHY ???

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top