Program Tip

Facebook의 소셜 플러그인에 유동 폭을 설정할 수 있습니까?

programtip 2020. 10. 25. 12:49
반응형

Facebook의 소셜 플러그인에 유동 폭을 설정할 수 있습니까?


"반응 형 디자인"개념을 중심으로 사이트를 개발 중이지만 페이스 북 소셜 플러그인은 정적 너비이며 크기가 조정되면 레이아웃이 "파괴"됩니다.

미디어 쿼리를 사용하여 저해상도 브라우저 (모바일 등)에서 숨기도록 플러그인을 설정했습니다. 그러나 데스크톱 브라우저에서 브라우저 창 크기가 더 작아 지지만 플러그인을 숨길만큼 작지 않으면 레이아웃에서 벗어날 수 있습니다.

Facebook 소셜 플러그인의 유동 폭을 설정하는 방법이 있습니까?


정답은 여기에서 찾은 것들의 조합입니다. Mikel의 대답은 좋은 시작입니다.

Facebook 개발자 플랫폼 링크

이것은 말한다 :

우리는 이에 대한 수정을 추진했습니다. 이제부터는 너비를 100 % (예 : data-width = "100 %")로 지정하여 유동적 인 레이아웃을 얻을 수 있습니다. 문서도 업데이트됩니다 : https://developers.facebook.com/docs/plugins/comments 양해 해 주셔서 감사합니다.

하지만 ... 이것은 로딩 시간에 플러그인에서 사용할 수있는 너비를로드합니다. 페이지 크기를 조정하면 페이지를로드 할 때와 동일한 너비로 유지됩니다. 이 문제를 해결하고 Facebook Social Plugin의 실제 반응 형 버전을 만들려면 CSS에 다음을 추가하세요.

.fb-comments, .fb-comments iframe[style], .fb-comments span {
   width: 100% !important;
}

이렇게하면 창 크기를 조정할 때 플러그인 크기가 사용 가능한 공간으로 조정됩니다.

이 코드가 페이지 플러그인에서 작동하도록하려면 클래스 이름 'fb-comments'를 'fb-page'로 변경하십시오.

.fb-page, .fb-page iframe[style], .fb-page span {
    width: 100% !important;
}

(Black_Stormy를 추가해 주셔서 감사합니다!)


이 방법 중 어느 것도 효과가 없었지만이 아이디어를 사용하면 다음이 효과적이었습니다.

.fb-comments, .fb-comments span, .fb-comments.fb_iframe_widget span iframe {
    width: 100% !important;
}

CSS를 사용하여 해결책을 찾았습니다. 이 기사에서 영감을 얻었습니다. http://css-tricks.com/2708-override-inline-styles-with-css/

.fb-comments, .fb-comments iframe[style] {width: 100% !important;}

이 코드를 사용하여 작동하도록 관리했습니다.

.fb-like, .fb-like span, .fb-like.fb_iframe_widget span iframe {
    width: 100% !important;

}

내 html 파일에 다음이 있기 때문입니다.

<div class="fb-like" data-href="http://www.yourwebsite.yourdomain" data-send="true"  data-show-faces="false" data-colorscheme="light" data-font="verdana"></div>

팁 : div 클래스에 따라 CSS를 변경해야합니다.


오래된 질문이지만 이제는 "페이스 북 댓글 플러그인 반응 형"에 대한 최고의 Google 결과이므로 여전히 관련성이 있습니다.

FB가 최근 (2014 년 5 월)이 문제를 마지막으로 수정했기 때문에 다른 답변의 해결 방법은 더 이상 필요하지 않습니다.

에서 https://developers.facebook.com/x/bugs/256568534516879/ :

우리는 이에 대한 수정을 추진했습니다. 이제부터는 너비를 100 % (예 : data-width = "100 %")로 지정하여 유동적 인 레이아웃을 얻을 수 있습니다. 문서도 업데이트됩니다 : https://developers.facebook.com/docs/plugins/comments 양해 해 주셔서 감사합니다.

이제 HTML을 다음과 같이 업데이트 할 수 있습니다.

<div class="fb-comments" data-width="100%" data-href="http://yourpageurl.com"></div>

추가 CSS 해결 방법이 필요하지 않습니다.

편집 :로드시 사용 가능한 공간에 맞게 너비를 조정하는 플러그인을 만듭니다. 브라우저 창의 크기를 조정할 때 플러그인은 초기 너비로 유지됩니다. 반응 형으로 만들려면 CSS에 다음을 추가하세요.

.fb-comments, .fb-comments iframe[style], .fb-comments span {
   width: 100% !important;
}

이렇게하면 브라우저 크기를 조정할 때 플러그인이 현재 사용 가능한 공간에 맞게 조정됩니다.


모바일 스니핑 페이스 북으로 인해 공식 워드 프레스 페이스 북 플러그인을 사용하는 경우.

모바일 버전은 모바일 장치 사용자 에이전트가 감지되면 자동으로 표시됩니다. 모바일 매개 변수를 false로 설정하여이 동작을 끌 수 있습니다. 참고 : 모바일 버전은 너비 매개 변수를 무시하고 대신 세로 / 가로 전환 상황에서 크기를 잘 조정하기 위해 100 %의 유동적 너비를 사용합니다. 이 동작을 활용하려면 모바일 사이트의 CSS를 조정해야 할 수 있습니다. 원하는 경우 컨테이너 요소를 통해 너비를 제어 할 수 있습니다. http://developers.facebook.com/docs/reference/plugins/comments/

35 행에서 facebook / social-plugins / fb-comments.php를 변경해야합니다.

<div class="fb-comments fb-social-plugin" ' . $params . ' data-mobile="false"></div>

이렇게하면 아래와 같이 스타일을 지정할 수 있습니다.

.fb-social-plugin {
    width:98%!important;

}

.fb_iframe_widget span {
    width:100%!important;
}

.fb-comments iframe[style] {width: 100% !important;}

모바일 버전을 수정하거나 플러그인 GUI에 설정을 지정할 수 있다면 좋을 것입니다.


.fb-comments span스타일 을 추가하는 것만으로도 확실히 작동 합니다.

.fb-comments, .fb-comments span, .fb-comments iframe[style] {width: 100% !important;}

수락 된 답변이 저에게 효과적이지 않았습니다.

Craig Bailey의 의견을 여기에서 찾았습니다.

http://www.wpresponsive.com/how-to-make-facebook-comments-responsive-wordpress

완벽하게 유동적입니다 (osx ff & safari, ios6에서 테스트 됨).

.fb-comments, .fb-comments iframe[style], .fb-comments span {
width: 100% !important;
}

이 게시물은 그리 오래되지 않았지만 대답이 저에게 효과가 없었던 것 같습니다. 나는 이것을 내 스타일 시트에 추가해야했다 ...

#fbcomments, .fb_iframe_widget, .fb_iframe_widget[style], .fb_iframe_widget iframe[style], #fbcomments iframe[style] {width: 100% !important;}

.fb_iframe_widget과 .fb_iframe_widget [style] 둘 다 중요해 보였습니다.


이 간단한 스크립트를 사용하여이 작업을 수행했습니다 (링크의 코드 참조).

https://gist.github.com/2111366

Facebook 앱 ID 및 페이지 URL을 사용하려면 정보를 몇 가지 변경해야합니다.

이 솔루션은 jQuery를 사용하므로 작동 방식을 이해해야하지만 일단 반응 형 디자인을 실행하는 스크립트를 얻으면 페이지로드 또는 페이지 크기 조정시 작동합니다.


이 크기 조정 항목에 대한 중요한 참고 사항 : Facebook 댓글 스크립트가 사용자가 모바일 장치에 있음을 감지하면이를 중단합니다. 그러나 <fb:comments>태그에 속성 값이 포함 되도록하면 mobile="false"(당분간) Facebook의 스크립트는 CSS를 존중합니다.


활동 피드 또는 좋아요 상자와 같은 Facebook 플러그인에 HTML5 코드를 사용하는 것을 선호하는 사용자 :

/******* IPHONE PORTRAIT MODE (480px or less) *******/
@media only screen and (min-width: 480px) and (max-width: 767px) {
    .fb_iframe_widget span[style], .fb_ltr[style] {
    width:420px !important;
    }
}
  • 주석 또는 백분율 기반 너비에서는 작동하지 않습니다. 순수한 유동성이 필요한 경우 iframe 코드를 고수하십시오.
  • 이 페이지 상단에있는 css-tricks 링크를 위해 Alan 에게 H / T. (:

CSS 파일이나 스타일 태그가있는 html 코드에 넣으십시오 !!!

<style>
.fb-comments, .fb-comments iframe[style], .fb-like-box, .fb-like-box iframe[style]{width:100% !important;}
.fb-comments span, .fb-comments iframe span[style], .fb-like-box span, .fb-like-box iframe     span[style]{width: 100% !important;}
</style>

참고 : http://dwij.co.in/making-facebook-comments-responsive


2015 년 9 월 현재,이 문제에 대한 저만의 해결책으로 정보가없는 대중과 합류 :

Facebook은 ( 문서 에 따라) fb-page라는 위젯에 대한 옵션을 제공합니다.이 옵션 은 부모의 너비 (최대 너비 :)를 추적해야합니다 . 로 다시 렌더링 할 때 실제 위젯 자체에 설정 한 내용에도 불구하고 위젯이 부모의 컨테이너 너비에 대해 이상한 값에 멈춰있는 것처럼 보입니다. 현재로서는 이것으로 충분합니다.adapt-container-width500pxFB.XFBML.parse()

  1. FB의 코드 생성기를 사용하여 요소 생성 ( 이 페이지 상단 )
  2. windowresize메서드에 이벤트를 바인딩합니다 (선택적으로 _.debounce중간 요청으로 브라우저 오버로드를 방지하기 위해 합리적인 제한과 함께 사용)
  3. 페이스 북이 위젯 API를 더 많이 노출 할 때까지 기다리면 무슨 일이 벌어지고 있는지 알 수 있습니다.

    <div class="fb-page"
        data-adapt-container-width="false" <!-- This bit's the important part -->
        data-href="https://www.facebook.com/yourpage"
        data-show-posts="true"
        data-small-header="true"
        data-width="100%"
    >
        <div class="fb-xfbml-parse-ignore">
            <blockquote cite="https://www.facebook.com/yourpage"><a href="https://www.facebook.com/yourpage">Like YourPage on Facebook!</a></blockquote>
        </div>
    </div>
    

다음 자바 스크립트와 결합 :

    // FB Resize
    $(window).bind('resize', _.debounce(function() {

        if (window.FB && FB.XFBML && FB.XFBML.parse) {
            var el = $('.fb-page');
            var width = el.parent().width();
            el.attr('data-width', width);

            FB.XFBML.parse();
        }
    }, 1000)); // Debounce until 1000ms have passed

이것은 JQuery이며 질문에 대한 답변의 일부일 수 있습니다. HTML5 버전의 like 버튼을 사용하고 있습니다.

<div class="fb-like" data-href="my.domain.com" data-layout="standard" data-send="false" data-width="255" data-show-faces="false" data-action="recommend" data-font="verdana"></div>

"div.main-content"요소는 좋아요 버튼이 제 디자인에 꼭 맞아야하는 요소입니다. 크기 조정은 div가 너무 작아 질 때까지 작동하여 div.fb-like의 data-layout 속성을 "표준"에서 더 적은 수평 공간을 차지하는 대안으로 변경해야합니다. 나는 이것에 익숙하지 않기 때문에 이것이 좋아요 버튼을 반응시키는 가장 우아한 해결책인지 확실하지 않습니다. 이 주제에 대해 좀 더 전문가 인 누군가로부터이 질문에 대한 답변을보고 싶습니다.

$(window).resize(function() {
  var computed_width = $('div.main-content').width();    
  $('div.fb-like iframe').attr('style', 'border: medium none; overflow: hidden; height:  24px; width: ' + computed_width + 'px');
});

inspect 요소를 사용하여 생성되는 코드를 확인합니다. Wordpress Facebook 플러그인과 같은 경우에는 다른 "ID"를 사용하고 사용중인 ID를 찾으면 추가

 #fbSEOComments, #fbSEOComments iframe[style] {width: 100% !important;}

이것은 항상 배우는 트릭을 수행하지는 않습니다. 색상과 크기를 변경할 수 있지만 반응 형으로 만드는 것은 여전히 ​​매우 버그가 있습니다. 백분율을 좋아하지 않는 것 같고 상자의 크기가 표시되지 않아 작동하지 않습니다. 브라우저 창의 크기에 따라 크기를 조정하기 위해 @media 쿼리를 수행합니다.

너비를 인식하면 좋겠지 만 @media가 유일한 방법 인 것 같습니다.


Facebook은 댓글 플러그인에서 출력 된 마크 업을 일부 변경했습니다. HTML5 버전을 사용하고 있습니다. 이것은 위에서 공유 된 것의 수정 된 CSS가 트릭을 수행했습니다.

.fb-comments, .fb_iframe_widget iframe[style], .fb_iframe_widget span[style] {width: 100% !important;}

다음은 regex 표현식을 사용하여 너비 만 다시 작성하고 나머지 스타일 태그는 그대로 두므로 출력 마크 업의 변경 사항에도 지속되어야하는 jquery입니다.

올바른 컨테이너 ID 또는 선택기를 지정해야합니다. 예를 들어 # footer-last. iframe은 반응 형으로 설정해야하는 컨테이너의 너비 변경에 따라 크기가 조정됩니다.

// Resize facebook window width
container_width = $('#footer-last').width();
$fb_iframe = $('.fb-social-like-plugin iframe');
fb_style = $fb_iframe.attr('style').replace(/width:\s*\d+px/i, 'width: ' + container_width + 'px');
$fb_iframe.attr('style', fb_style);

댓글에 대해서는 모르겠지만 링크 상자를 사용하면 Facebook에서 직접 iframe 옵션을 사용하고 백분율로 픽셀 단위의 너비를 전환하면됩니다. 열이 있습니다.


다음은 HTML5 Facebook LikeBox 플러그인을 응답 높이 또는 너비와 함께 DOM에 추가하는 작은 해결 방법입니다.

        $(document).ready(function(){      
            var height = $(window).height();
            var width = $(window).width();

            var widget_height = parseInt((height)*0.9);
            var widget_width = parseInt((height)*0.3);
            var page_url = "http://www.facebook.com/Facebook";

            $(".fb-plugin").append("<div class='fb-like-box' 
                                         data-href='"+page_url+"' 
                                         data-width='"+widget_width+"' 
                                         data-height='"+widget_height+"' 
                                         data-colorscheme='dark' 
                                         data-show-faces='true' 
                                         data-border-color='#222' 
                                         data-stream='true' 
                                         data-header='true'>
            </div></div>");
        });

다음은 응답 너비와 로딩 이미지가있는 jQuery를 사용하는 완전한 예입니다. Alan과 Jubair의 CSS 코드가 코드에 주석으로 표시됩니다.

Android webview에서 잘 작동합니다.

<html>
<head>
    <title>Title</title>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<style>
    .fb-comments, .fb-comments span, .fb-comments.fb_iframe_widget span iframe {
        width: 100%;/* !important; To get the control with JQuery*/
    }
</style>

<body>
    <div id="fb-root"></div>
    <script>
       window.fbAsyncInit = function() {
        FB.init({
                appId   : 'APP_ID',
                channelUrl : '//domain.com/channelUrl.php',
                status  : true, 
                cookie  : true,
                xfbml   : true
            });

        //Event fired when the plugin has been completely loaded
        FB.Event.subscribe('xfbml.render',
            function(response) {
                //alert('You liked the URL: ' + response);
                var w = (typeof window.innerWidth != 'undefined')?
                           window.innerWidth
                        :(typeof document.documentElement != 'undefined'
                         && typeof document.documentElement.clientWidth !=
                         'undefined' && document.documentElement.clientWidth != 0) ?
                           document.documentElement.clientWidth
                        : document.getElementsByTagName('body')[0].clientWidth;

                w *= .950; //95% for best fit on mobile screens
                //RESIZE
                $(".fb-comments").css("width",w);
                $(".fb-comments > span").css("width",w);
                //Some days ago the next line would be sufficient                       
                $(".fb_ltr").css("width",w);
                //Now the modify of the span width is necessary to do the work

                $("#div_loading_gif").remove();



            }
        );

      };

      //cargando SDK Asíncronamente
      (function(d){
            var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
            if (d.getElementById(id)) {return;}
            js = d.createElement('script'); js.id = id; js.async = true;
            js.src = "//connect.facebook.net/en_US/all.js";
            ref.parentNode.insertBefore(js, ref);
      }(document));



    </script>

    <div id="div_loading_gif" style="width:100%;  height:100%; text-align:center; background:url(../img/loading.gif) no-repeat center center;" >

    </div>

    <!--Usando jquery modificar el style de el div de clase fb_ltr
    cambiar el ancho por el de la pantalla-->
    <div class="fb-comments"
        style="padding:0 auto;"
        data-href="http://domain.com/comments.html" 
        data-width="100px" 
        data-num-posts="5"
        data-mobile="false"
        >
    </div>



</body>


I think max-width is better than width in this case, and it works for me:

.fb-comments, .fb-comments iframe[style], .fb-comments span {
  width: 100% !important;
}

This works for me

/* Set inline instead of inline-block */
.fb-comments.fb_iframe_widget{
    display: inline !important;
}

.fb-comments.fb_iframe_widget span,
.fb_iframe_widget iframe {
    width: 100% !important;
}

I've just tried this and it appears there is now a <div> within the iframe that has a fixed width, meaning you now actually need to remove the style tag with javascript to make it fluid.

EDIT: You can't access the iframe content with JS because it's coming from another domain


Create an empty div where you want the facebook like box to be (or other social plug-in, works universally) with a class 'fb-container', then add the following jQuery:

$(document).ready(function(){
    $('.fb-container').replaceWith('<div class="fb-comments" data-href="https://WWW.YOURSITEHERE.COM/" data-width="' + $('PARENT DIV').width().toFixed(0) +'" data-numposts="5" data-colorscheme="light"></div>');
});

p.s. you can replace PARENT DIV with any other element you want the comment box to match and WWW.YOURSITEHERE.COM with your site


This works for me:

 $('.fb-comments').attr('data-width', '100%');

I got it working using a little jQuery and setting the "data-width" attribute when the page loads and on window resizing. Problem I ran into with all the CSS approaches is that some of the comments and buttons were hidden outside the container's margins or overflowing.

Here's my $0.02, hope it helps. Also, just set the #content selector to whatever you want the comment box to match such as a container div...

jQuery(document).ready(function() {

//check for device width and reformat facebook comments
function fbCommentWidth() {
    jQuery('.fb-comments').attr('data-width',jQuery('#content').width());

}
//run on resize, and reparse FB comments box    
jQuery(window).on('resize',function() {
    fbCommentWidth();
    FB.XFBML.parse();
});
//run on document ready
fbCommentWidth();

});


That's how it works: just add this data-width="100%" Here is an example:

<div class="fb-comments" data-href="<?php the_permalink(); ?>" data-numposts="5" data-colorscheme="light" data-width="100%"></div>

Here is what I ended up with:

(function() {
    window.addEventListener('load', updateWidth);
    window.addEventListener('resize', debounce(function () {
        updateWidth();
        if (window.FB && FB.XFBML && FB.XFBML.parse) {
            FB.XFBML.parse();
        }
    }, 1000));

    function updateWidth() {
        $('.fb-like, .fb-comments').each(function () {
            var el = $(this);
            var width = el.parent().width();
            el.attr('data-width', width);
        })
    }

    function debounce(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    }
})();

참고URL : https://stackoverflow.com/questions/6500424/is-it-possible-to-set-a-fluid-width-for-facebooks-social-plugins

반응형