728x90

자바스크립트에서 숫자를 표기할때 3자리마다 콤마를 찍어줘야 할 때가 있다 자주 사용하는 기능인데 매번 만들기란 여간 귀찮은게 아니다.

콤마찍기

1
2
3
4
5
//콤마찍기
function comma(str) {
    str = String(str);
    return str.replace(/(\d)(?=(?:\d{3})+(?!\d))/g, '$1,');
}

콤마풀기

1
2
3
4
5
//콤마풀기
function uncomma(str) {
    str = String(str);
    return str.replace(/[^\d]+/g, '');
}

복사 붙여넣기로 사용하자!

input box에서 사용자 입력시 바로 콤마를 찍어주기 위한 함수도 추가 한다.

1
2
3
4
5
function inputNumberFormat(obj) {
    obj.value = comma(uncomma(obj.value));
}
 
//<input type="text" onkeyup="inputNumberFormat(this)" />

 

728x90

(PHP 5, PHP 7)

mysqli::query -- mysqli_query — Performs a query on the database

설명 ¶

객체 기반 형식

mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

절차식 형식

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

Performs a query against the database.

For non-DML queries (not INSERT, UPDATE or DELETE), this function is similar to calling mysqli_real_query()followed by either mysqli_use_result() or mysqli_store_result().

Note:

In the case where you pass a statement to mysqli_query() that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysqlclient). The behavior is as follows:

  • mysqlnd on Linux returns an error code of 1153. The error message means "got a packet bigger thanmax_allowed_packet bytes".

  • mysqlnd on Windows returns an error code 2006. This error message means "server has gone away".

  • libmysqlclient on all platforms returns an error code 2006. This error message means "server has gone away".

인수 ¶

link

순차 형식 전용: mysqli_connect()나 mysqli_init()가 반환한 연결 식별자.

query

The query string.

Data inside the query should be properly escaped.

resultmode

Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

If you use MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result()

With MYSQLI_ASYNC (available with mysqlnd), it is possible to perform query asynchronously. mysqli_poll()is then used to get results from such queries.

반환값 ¶

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

변경점 ¶

버전설명
5.3.0Added the ability of async queries.

예제 ¶

Example #1 mysqli::query() example

객체 기반 형식

<?php
$mysqli 
= new mysqli("localhost""my_user""my_password""world");

/* check connection */
if ($mysqli->connect_errno) {
    
printf("Connect failed: %s\n"$mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    
printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    
printf("Select returned %d rows.\n"$result->num_rows);

    
/* free result set */
    
$result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result $mysqli->query("SELECT * FROM City"MYSQLI_USE_RESULT)) {

    
/* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    
if (!$mysqli->query("SET @a:='this will not work'")) {
        
printf("Error: %s\n"$mysqli->error);
    }
    
$result->close();
}

$mysqli->close();
?>

절차식 형식

<?php
$link 
mysqli_connect("localhost""my_user""my_password""world");

/* check connection */
if (mysqli_connect_errno()) {
    
printf("Connect failed: %s\n"mysqli_connect_error());
    exit();
}

/* Create table doesn't return a resultset */
if (mysqli_query($link"CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    
printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result mysqli_query($link"SELECT Name FROM City LIMIT 10")) {
    
printf("Select returned %d rows.\n"mysqli_num_rows($result));

    
/* free result set */
    
mysqli_free_result($result);
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result mysqli_query($link"SELECT * FROM City"MYSQLI_USE_RESULT)) {

    
/* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    
if (!mysqli_query($link"SET @a:='this will not work'")) {
        
printf("Error: %s\n"mysqli_error($link));
    }
    
mysqli_free_result($result);
}

mysqli_close($link);
?>

위 예제들의 출력:

Table myCity successfully created.
Select returned 10 rows.
Error: Commands out of sync;  You can't run this command now

참고 ¶

add a note add a note

User Contributed Notes 21 notes

petrus.jvr ¶
6 years ago
When calling multiple stored procedures, you can run into the following error: "Commands out of sync; you can't run this command now".
This can happen even when using the close() function on the result object between calls. 
To fix the problem, remember to call the next_result() function on the mysqli object after each stored procedure call. See example below:

<?php
// New Connection
$db = new mysqli('localhost','user','pass','database');

// Check for errors
if(mysqli_connect_errno()){
echo 
mysqli_connect_error();
}

// 1st Query
$result $db->query("call getUsers()");
if(
$result){
     
// Cycle through results
    
while ($row $result->fetch_object()){
        
$user_arr[] = $row;
    }
    
// Free result set
    
$result->close();
    
$db->next_result();
}

// 2nd Query
$result $db->query("call getGroups()");
if(
$result){
     
// Cycle through results
    
while ($row $result->fetch_object()){
        
$group_arr[] = $row;
    }
     
// Free result set
     
$result->close();
     
$db->next_result();
}
else echo(
$db->error);

// Close connection
$db->close();
?>
theyranos at gmail dot com ¶
6 years ago
The cryptic "Couldn't fetch mysqli" error message can mean any number of things, including:

1. You're trying to use a database object that you've already closed (as noted by ceo at l-i-e dot com). Reopen your database connection, or find the call to <?php mysqli_close($db); ?> or <?php $db->close(); ?> and remove it.
2. Your MySQLi object has been serialized and unserialized for some reason. Define a wakeup function to re-create your database connection. http://php.net/__wakeup 
3. Something besides you closed your mysqli connection (in particular, see http://bugs.php.net/bug.php?id=33772)
4. You mixed OOP and functional calls to the database object. (So, you have <?php $db->query() ?> in the same program as <?php mysqli_query($db?>).
registrations at jdfoxmicro dot com ¶
7 years ago
I like to save the query itself in a log file, so that I don't have to worry about whether the site is live. 

For example, I might have a global function: 

<?php 
function UpdateLog $string $logfile )  { 
   
$fh fopen $logfile 'a' ); 
   
$fwrite $fh strftime ('%F %T %z')." ".$string."\n"
   
fclose $fh ); 

?> 

Then in my mysql function error trapper, something like this: 

<?php 
   $error_msg 
"Database error in [page].php / "
   
$error_msg .= mysqli_error $link )." / "
   
$error_msg .= $query
   
UpdateLog $error_msg DB_ERROR_LOG_FILE ); 
?> 

I also include the remote IP, user agent, etc., but I left it out of these code samples.  And have it e-mail me when an error is caught, too. 

Jeff
Beeners ¶
12 years ago
Stored Procedures.

Use mysqli_query to call a stored procedure that returns a result set. 

Here is a short example:

<?php
$mysqli 
= new mysqli(DBURI,DBUSER,DBPASS,DBNAME);
if (
mysqli_connect_errno()) 
{
  
printf("Connection failed: %s\n"mysqli_connect_error());
  exit();
}

$SQL "CALL my_procedure($something)";
if ( (
$result $mysqli->query($SQL))===false )
{
  
printf("Invalid query: %s\nWhole query: %s\n"$mysqli->error$SQL);
  exit();
}

while (
$myrow $result->fetch_array(MYSQLI_ASSOC))
{
  
$aValue[]=$myrow["a"];
  
$bValue[]=$myrow["b"];
}
$result->close();
$mysqli->close();
?>
I hope this saves someone some time.
joseph_robert_martinez at yahoo dot com ¶
3 years ago
For those using with replication enabled on their servers,  add a mysqli_select_db() statement before any data modification queries.  MySQL replication does not handle statements with db.table the same and will not replicate to the slaves if a scheme is not selected before.

Found out after days of resetting master and slaves on another site http://www.linuxquestions.org/questions/linux-server-73/mysql-5-1-not-replicating-properly-with-slave-823296/
NUNTIUS ¶
9 years ago
This may or may not be obvious to people but perhaps it will help someone. 

When running joins in SQL you may encounter a problem if you are trying to pull two columns with the same name. mysqli returns the last in the query when called by name. So to get what you need you can use an alias. 

Below I am trying to join a user id with a user role. in the first table (tbl_usr), role is a number and in the second is a  text name (tbl_memrole is a lookup table). If I call them both as role I get the text as it is the last "role" in the query. If I use an alias then I get both as desired as shown below. 

<?php 
$sql 
"SELECT a.uid, a.role AS roleid, b.role, 
            FROM tbl_usr a 
            INNER JOIN tbl_memrole b 
            ON a.role = b.id 
            "


    if (
$result $mysqli->query($sql)) { 
        while(
$obj $result->fetch_object()){ 
            
$line.=$obj->uid
            
$line.=$obj->role
            
$line.=$obj->roleid
        } 
    } 
    
$result->close(); 
    unset(
$obj); 
    unset(
$sql); 
    unset(
$query); 
    
?> 
In this situation I guess I could have just renamed the role column in the first table roleid and that would have taken care of it, but it was a learning experience.
omidbahrami1990 at gmail dot com ¶
1 month ago
This Is A Secure Way To Use mysqli::query
--------------------------------------------------------
<?php
function secured_query($sql)
{
$connection = new mysqli($host,$username,$password,$name);
    
if (
$connection->connect_error
die(
"Secured");
    
$result=$connection->query($sql);
if(
$result==FALSE)
die(
"Secured");
    
$connection->close();        
return 
$result;    
}
/*
$host ---> DataBase IP Address
$username ---> DataBase Username
$password ---> DataBase Password
$name ---> DataBase Name
*/
?>
ceo at l-i-e dot com ¶
9 years ago
Translation:
"Couldn't fetch mysqli"

You closed your connection and are trying to use it again.

It has taken me DAYS to figure out what this obscure error message means...
Anonymous ¶
9 months ago
I don't know is it bug or something , then first I write it here . Query SHOW with MYSQLI_USE_RESULT option don't show num_rows :
<?php
SHOW TABLES LIKE 
[some table], MYSQLI_USE_RESULT
num_rows 
// shows 0 !
?>
ahmed dot 3abdolah at gmail dot com ¶
3 years ago
Hi, i created function that add  a new table using array , i work with it on my projects ...
<?PHP
                   
/* this function was learned from PHP.net */
function array_keys_exist(&$key,array &$array){
                
$keys split("\|",$key);
                foreach(
$keys as $key_s){
                    if(
array_key_exists($key_s$array)) return true;
                    }
                return 
false;
            }
/*and this is my function */
array_create_table(array &$array){
        if(
is_array($array)){
           
$key "table|rows|values";    
        
$info "";
        if(
array_keys_exist($key,$array)){
        if(
is_array($array["rows"]) and is_array($array["values"]) ){
                                         
            if(
count($array["rows"]) == count($array["values"])) { 
                        for(
$i=0$i<=count($array["rows"]); $i++){
    
$info $info." ".$array["rows"][$i]." ".$array["values"][$i]." NOT NULL ";
            if(
$i count($array["rows"])-$info $info.","
                    }
    
$query "CREATE TABLE ".$this->private_tables_name.$array["table"]." ";
    
$query .= "( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, ".$info." )";
                    return 
$query;    
                        }
                        }
                }else return 
"Error";
                    }
            }

/* the use is simple */
$database = new database(); // connection to database i used mysqli ... 
$array = array("table"=>"MRO""rows"=>array("name","username") , "values" => array("VARCHAR (50) "," VARCHAR (50) ") );

$query array_create_table($array); // convert and create the query ...
if($database->query($query)) echo "Work"; else echo "Error"// result : work

?>
jcwebb at dicoe dot com ¶
10 years ago
When building apps, i like to see the whole statement when if fails.
<?php
$q
="SELECT somecolumn FROM sometable"//some instruction
$r=mysqli_query($DBlink,$q) or die(mysqli_error($DBlink)." Q=".$q);
?>
If theres an error (like my numerous typing mistakes) this shows the entire instruction.
Good for development (not so good on production servers - simply find and replace when finished: $r=mysqli_query($DBlink,$q); )

Hope it helps. Jon
marcus at synchromedia dot co dot uk ¶
6 years ago
The exact type returned by a successful query is mysqli_result.
thomas dekker ¶
7 years ago
Building inserts can be annoying. This helper function inserts an array into a table, using the key names as column names:

<?php
  
private function store_array (&$data$table$mysqli)
  {
    
$cols implode(','array_keys($data));
    foreach (
array_values($data) as $value)
    {
      isset(
$vals) ? $vals .= ',' $vals '';
      
$vals .= '\''.$this->mysql->real_escape_string($value).'\'';
    }
    
$mysqli->real_query('INSERT INTO '.$table.' ('.$cols.') VALUES ('.$vals.')');
  }
?>

Adapt it to your specific needs.
hunreal at gmail dot com ¶
13 years ago
Use difference collation/character for connect, result.
You can set the collation before your query.

E.g. want to set the collation to utf8_general_ci 
you can send the query "SET NAMES 'utf8'" first

<?php
$mysqli
=new mysqli('localhost''root''password''test');
$mysqli->query("SET NAMES 'utf8'");
$q=$mysqli->query("select * from test");
while(
$r=$q->fetch_assoc()) {
    
print_r($r);
}
?>

There are many variables about character settings.
By running sql command, SHOW VARIABLES LIKE 'char%'; 
There are some variables control the character usage.

character_set_client
character_set_connection
character_set_database
character_set_results
character_set_server
character_set_system

Also SET NAMES can repalce with one or some settings like SET character_set_results='utf8';
info at ff dot net ¶
11 years ago
Calling Stored Procedures

Beeners' note/example will not work. Use mysqli_multi_query() to call a Stored Procedure. SP's have a second result-set which contains the status: 'OK' or 'ERR'. Using mysqli_query will not work, as there are multiple results.

<?php
$sQuery
="CALL SomeSP('params')";
if(!
mysqli_multi_query($sqlLink,$sQuery)) {
  
// your error handler 
}
$sqlResult=mysqli_store_result($sqlLink);

if(
mysqli_more_results($this->sqlLink))//Catch 'OK'/'ERR'
  
while(mysqli_next_result($this->sqlLink));
?>

You will have to rewrite/expand this a bit for more usability of course, but it's just an example.
andrey at php dot net ¶
12 years ago
WARNING: This function was buggy on 64bit machines till 5.0.5. Affected versions 5.0.0-5.0.4. The problem appears when a value for the third parameter is passed - this will lead to instant FALSE returned by the function. Therefore if you need to use unbuffered query don't use this function with the aforementioned versions but you mysqli_real_query() and mysqli_use_result().
If you have the rights to patch you PHP installation the fix is easy:
In file ext/mysqli/myslqi_nonapi.c, function PHP_FUNCTION(mysqli_query)
change
unsigned int resultmode=0;
to
unsigned long resultmode=0;

Thanks!
Igor ¶
9 years ago
mysqli::query() can only execute one SQL statement.

Use mysqli::multi_query() when you want to run multiple SQL statements within one query.
popere dot noel at yahoo dot com ¶
4 years ago
or you could just extend the class...
in my case i already had a wraper for the db so something like this was easy :

public function  free($result) {
  
  $result->free_result();
$this->link->next_result();
}

just tried it and it works like a charm ;-)
David Marcus ¶
8 months ago
If you use the default resultmode of MYSQLI_STORE_RESULT, you can call $mysqli->close() right after $mysqli->query and before you use mysqli_result. This reduces the time the connection is open, which can help if the database server has a limit on how many connections there can be.
blinki bill, argodak at yahoo dot com ¶
4 years ago
Recently I had puzzling problem when performing DML queries, update in particular, each time a update query is called and then there are some more queries to follow this error will show on the page and go in the error_log:
"Fatal error:  Exception thrown without a stack frame in Unknown on line 0"

The strange thing is that all queries go through just fine so it didn't make much sense:

$update = mysqli_query($connection, $query_string);
if(!$update){
echo 'Houston we have a problem '.mysqli_error($connection);
exit;
}

In the above example "$update" is "true", mysqli_error() is empty and of course the update operation goes through, however the nasty super cryptic error appears on the page.
What makes even less sense to me is how I fixed it - just called "mysqli_free_result" after the update query and the problem was gone, however because mysqli_free_result is not supposed to be called after DML queries (to free what, a boolean? lol) it needs to be wrapped in a try catch block:

try{
mysqli_free_result($update);
}catch (Exception $e){
//do nothing
}

So, I don't know why but it seems that when DML queries are responsible for:
"Fatal error:  Exception thrown without a stack frame in Unknown on line 0"
calling "mysqli_free_result" after the query seems to be fixing the issue
antiriad at gmail dot com ¶
10 years ago
this is a variant of mysqli_query that returns output parameters as a rowset.

<?php
  
function mysqli_exec($link$command)
  {
      
$select '';
      
$i2 0;
      
      while (
true)
      {
      
$i1 strpos($command'@'$i2);
      
      if (
$i1 === false)
          break;
          
      
$field '';
      
$i2 $i1 1;
      
      while (
$i2 strlen($command) && 
          (
$command[$i2] >= '0' && $command[$i2] <= '9') ||
          (
$command[$i2] >= 'A' && $command[$i2] <= 'Z') ||
          (
$command[$i2] >= 'a' && $command[$i2] <= 'z') ||
          (
$command[$i2] == '_'))
          
$i2++;
          
      
$field substr($command$i1 1$i2 $i1 1);
          
      if (
strlen($select) == 0)
        
$select "select @{$field} as $field";
      else                    
          
$select $select ", @{$field} as $field";
      }
      
      if (
strlen($select) > 0)
      {      
        
mysqli_query($link$command);
        return 
mysqli_query($link$select);
      }
      else
        return 
mysqli_query($link$command);
  }
?>

an example:

<?php
  $link 
mysqli_connect('localhost''myusr''mypass') or die ('Error connecting to mysql: ' mysqli_error($link));
  
mysqli_select_db($link'clips');
  
  
$user_name 'test';
  
$result mysqli_exec($link"call do_user_login('$user_name', @session_id, @msg)");
  
  while (
$row mysqli_fetch_assoc($result))
  {
    echo 
"session_id : {$row['session_id']} <br>";
    echo 
"msg        : {$row['msg']} <br>";
  }
?>


'DB' 카테고리의 다른 글

SQL Database Performance Tuning for Developers  (0) 2018.04.10
[MSSQL]sqlsrv_fetch_array  (0) 2018.02.05
[MSSQL]sqlsrv_execute  (0) 2018.02.05
jQuery mouseleave()  (0) 2018.01.14
mysqli_result::fetch_array  (0) 2018.01.14
728x90

안녕하세요. 오늘은 jQuery 스크립트를 사용해서

따라다니는 사이드바를 만들어 보겠습니다.


예전에 화면에 아예 고정되고 따라다니는 플로팅 메뉴를 만든적이 있긴한데

http://cocosoft.kr/149 - 플로팅메뉴(추천위젯,광고)

오늘은 사이드바의 메뉴 하나 또는 몇개만! 움직이는 따라다니면서 움직이는 형태를 알려드리겠습니다.


당연히 사용 전제 조건으로 jQuery 사용해야겠죠?

요즘 웬만한 스킨이나 티스토리 공식 반응형 웹 스킨등에서도 jQuery를 사용하고 있긴합니다.


완성된 예제 입니다.


스킨의 상관없이 기존 사이드바 div 태그에 값만 설정 추가 해주면

어느 사이드바에서도 사용이 가능합니다.

intro - 사이드바에 대한 고찰

요즘 티스토리에서도 반응형 웹스킨을 공식적으로 지원하고 있고


해외 포럼이나 해외 블로그, 반응형 사이트들을 살펴보면

모바일 디자인과 친화성을 위해서인지 1단 또는 2단형 반응형으로 개발 되는 경우가 많습니다.

구식 브라우저의 호환성도 높이고 깔끔한 디자인으로 포스트 본문에 집중도 잘 되는 것 같습니다.

아예 사이드바 카테고리를 숨겨놓거나 좌측이나 우측 사이드에 고정하는 방식을 많이 사용합니다.



해외 타임지 사이트도 사이드바만 따로 고정되어있는 형태고

티스토리 공식 반은형 스킨도 현재 2가지 형태를 제공하고 있습니다.


저도 이런 깔끔한 디자인이 마음에 들어서

아예 공식 스킨을 사용하거나 2단형식으로 바꿀까?도 고민중입니다.

하지만 이 형식의 단점도 존재합니다.

바로 고정된 사이드바에 광고를 게재시에 애드센스 광고 정책 위반이라는 점입니다.

position: fixed;형식으로 위치하게 되는데 이러한 사이드바 안에

광고를 집어넣게 되면 정책 위반으로 애드센스 수익과 계정이 정지 될 수 있습니다.


지금 티스토리 반응형 웹 공모전 이후 반응형 스킨들이 많이 퍼지면서

고정된 사이드바에 광고를 위치시키는 분들이 많은데

사이드바의 길이가 길어서 스크롤이 되어서 고정된 형태가 아닌 것 처럼 보여도

전부 정책 위반입니다. ㅠ_ㅠ 


저도 만약 사이드바의 애드센스 광고를 달지 않을 경우에는 해당 고정된 형태인 사이드바를 사용을 할 것 같습니다.

애드센스를 사용하시는 분들이라면 항상 정책 위반 ㅠ_ㅠ여부를 염두에 두고 해야합니다.

저도 스킨을 최근에 변경하면서 광고 정책을 위반하지 않으려고 스킨 여백 수정을 하고 있습니다.


만약 CCZ-CROSS 스킨 또는 티스토리 스킨을 사용하시는 분들중


우측이나 좌측에 고정된 형태의 사이드바를 사용하고 싶으신 분들은

SONYLOVE님의 게시글을 참고하세요!

http://sonylove.tistory.com/1132 - 티스토리 스킨 사이드바 고정하는 방법


본격적으로 시작!!!!!!!

이제 본격적으로 사이드바의 메뉴중

하나 또는 여러개만 스크롤을 내릴시 본문콘텐츠에 맞춰서

따라 내려가는 방법에 대해서 알아보겠습니다.

부드럽게 따라다니는 사이드바

우선 자바스크립트 소스를 붙혀넣기 해야됩니다.

해당소스는 http://blog.bits.kr/90 및 http://madebykaus.com/?p=300 를 참고해서

티스토리 블로그에 맞게 수정을 하였으며, 더자세한 속성값은 해당 포스트를 참고바랍니다.


html//css 수정에서 html 제일 하단 부분 </body> 에 붙혀넣기를 하면됩니다.

Markup

<script>
$(function(){
    var $win = $(window);
    var top = $(window).scrollTop(); // 현재 스크롤바의 위치값을 반환합니다.
 
    /*사용자 설정 값 시작*/
    var speed          = 500;     // 따라다닐 속도 : "slow", "normal", or "fast" or numeric(단위:msec)
    var easing         = 'linear'; // 따라다니는 방법 기본 두가지 linear, swing
    var $layer         = $('.float_sidebar'); // 레이어 셀렉팅
    var layerTopOffset = 0;   // 레이어 높이 상한선, 단위:px
    $layer.css('position', 'relative').css('z-index', '1');
    /*사용자 설정 값 끝*/
 
    // 스크롤 바를 내린 상태에서 리프레시 했을 경우를 위해
    if (top > 0 )
        $win.scrollTop(layerTopOffset+top);
    else
        $win.scrollTop(0);
 
    //스크롤이벤트가 발생하면
    $(window).scroll(function(){
        yPosition = $win.scrollTop() - 1100; //이부분을 조정해서 화면에 보이도록 맞추세요
        if (yPosition < 0)
        {
            yPosition = 0;
        }
        $layer.animate({"top":yPosition }, {duration:speed, easing:easing, queue:false});
    });
});
</script>
</body>
</html>

그리고 나서 따라다니게 하고 싶은 사이드바 모듈에

클래스 값 .float_sidebar을 넣어주면 됩니다.

Markup

<div class="float_sidebar"></div>

요런식으로 추가해도 됩니다!!


스크립트 부분에서 yPosition 수치만 잘 조절해주시면 쉽게 따라오는 메뉴를 만들 수 있습니다.

따라다니는 사이드바 메뉴도 마찬가지로 애드센스 영역을 따라다니게 해서는 안됩니다. 애드센스 광고 정책 위반입니다.


+추가 응용편)일정이상 내려가면 나타나게하기

위 방법은 사이드바 중간에 위치한 모듈도 클래스 값을 줘서 내릴 경우

사이드바의 위치 깨짐이 없이 내려가게 가능하나

보기에는 좋지 않겠죠?!ㅎㅎ

다른 사이드바 모듈을 다거치면서 내려오니깐요?


그래서 되도록이면 따라다니는 사이드바를 가장 아래 쪽으로 위치해주거나


아니면 일정 스크롤 이상 내려갔을 경우 나타나게 만들어 주면 되겠죠??

동일한 사이드바를 하나더 만들어서 가장 아래에 배치를 해주고

속성값은 display: none; 값을 줘서 보이지 않게 한 다음


아래 스크립트를 추가해서 일정 이상 내려갔을 경우 나타나게 해주면 되겠죠?


Markup

<script>
$(document).ready(function() {
    $(window).scroll(function() {
        $(this).scrollTop() > 1000 ? $(".float_sidebar").fadeIn() : $(".float_sidebar").fadeOut()
    })
});
</script>


따라다니는 사이드바 메뉴 배너 플로팅 박스들 만드는 방법은 다양하니!!

잘 참고하시면 될 것같아요.

이 방법을 응용 하시면 다양한 연출이 가능 할 것 같습니다.


굳이 부드럽게 이동하는 것을 원하지 않는 분들은 addClassremoveClass잘 사용하셔도

position:와 여백을 수정하게 해서!

고정되어 이동하는 카테고리를 잘 만들 수 있을 거라 생각합니다!!

Markup

<script>
	$(document).ready(function () {  
        var top = $('#float_sidebar').offset().top - parseFloat($('#float_sidebar').css('marginTop').replace(/auto/, 0));
        $(window).scroll(function (event) {
        var y = $(this).scrollTop();
  
       if (y >= top) {
          $('#float_sidebar').addClass('fixed');
       } else {
          $('#float_sidebar').removeClass('fixed');
      }
  });
});
</script>

이런식으로 말이죠.

결론

저도 지금 스킨을 바꾸면서 계속 수정을 하고 변경을 하고 있는 중입니다.

아예 사이드바를 고정할지

아니면 스크롤이 내리더라도 따라다니는 메뉴를 사용해서

 블로그 콘텐츠의 접근성을 높히는 방법을 사용할지


따로 addthis와 같은 추천글 플러그인을 사용해서 사용할지

(addthis는 유로 구매가 아니면 ㅠ 특정 추천글을 선택할 수 없는 아쉬움이 있습니다.)


계속 테스트를 해보고 결정을 해야 할 것 같습니다.

보조 블로그는 최신글 목록만 따라다는 사이드바를 적용 했는데

애드센스의 페이지 RPM이 소폭 증가 한 것을 알 수 있었습니다.


이것 때문이지는 모르겠지만 사이드바의 영역에 어느정도 추천 콘텐츠를 제공하는 것은

 방문객의 페이지 재방문을 조금이나마 높혀줄 수 있다고 생각합니다.!


그럼 다들 블로그에 사이드바 꾸미기를 잘하길 바라겠습니다.



출처: http://cocosoft.kr/361 [코코소프트]

출처: http://cocosoft.kr/361 [코코소프트]

출처: http://cocosoft.kr/361 [코코소프트]

출처: http://cocosoft.kr/361 [코코소프트]

+ Recent posts